Laravel阵列验证唯一,ID为

时间:2016-07-08 14:21:40

标签: laravel laravel-5.2 laravel-validation

如何在使用unique参数更新数据时使用id验证规则,以便在保存现有值时验证不会失败?

'columns.*.name' => 'required|unique:columns, name, id, columns.id'

id需要替换为数组中*的值,但我无法弄清楚如何。

3 个答案:

答案 0 :(得分:1)

你可以使用这样的东西

namespace App\Validations;

class ClientValidation
{

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public static function rules($client_id = "")
{
    return [
        'email'          => 'required|email|unique:shippers,email,'. $client_id,
        'first_name'     => 'required',
        'last_name'      => 'required',
        'company'        => 'required',
        'phone'          => 'required',
        'password'       => 'required',
    ];
}

/**
 * Get the specific message for rules that apply to the request.
 *
 * @return array of message
 */
public static function messages()
{
    return [
        //
    ];
}

}

这是我的自定义验证,因此您需要制作文件夹并将其放入..

答案 1 :(得分:0)

使用model id作为唯一规则的第三个参数来跳过当前记录:

public function rules()
{
    $id = $this->route('model')->id;

    return [
        'columns.*.name' => "required|unique:columns,name,{$id}"
    ];
}

如果在创建和更新模型时使用相同的表单请求类,请首先检查这是否是补丁请求:

$id = $this->method() == 'PATCH' ? $this->route('model')->id : null;

如果您不使用路线模型绑定,请替换' model'无论你传递给你的路线,都要实例化模型并传递它的身份。

答案 2 :(得分:0)

我最终实施了一个更复杂的解决方案,我认为它涵盖了所有可能性。

我从数据库中列出了给定列的所有当前值,包括限制where子句(这应该是可选的,但目前不是)。

然后我覆盖请求中包含的任何值。

最后,我计算请求中每个值的使用次数,并检查当前值是否被多次使用。

这可能会为每个重复值抛出多个验证失败,但我不认为这是一个问题。

<?php

namespace App\Providers;

use DB;
use Validator;

use Illuminate\Support\ServiceProvider;

class ValidationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        Validator::extend('array_unique', function($attribute, $value, $parameters, $validator) {
            $table = $parameters[0];
            $column = $parameters[1];
            $ref = $parameters[2];
            $id = $parameters[3];

            $values = DB::table($table)->where($ref, $id)->pluck($column, 'id');

            $attributes = explode(".", $attribute);
            $data = $validator->getData();

            $items = $data[$attributes[0]];

            foreach($items as $key => $item)
            {
                $values[$key] = $item[$attributes[2]];
            }

            $counts = array_count_values($values);

            return $counts[$value] < 2;
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
相关问题