L5.3 - 验证器 - 触发'unique'si时获取DB记录

时间:2017-03-24 08:29:18

标签: php laravel validation

我正在使用Validator验证输入:

$validator = Validator::make($request->all(), [
    'short'         => 'required',
    'name'          => 'required|unique:type_event,name'
]);

if ($validator->fails()) {
    // fails validation
}

unique检查被触发时,有没有办法接收id或已经存在于数据库中的记录?或者我可以通过以下方式调用模型:

$data = TypeEventModel::where('name', '=', $request->input('name'))->firstOrFail();

谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您需要一个自定义验证规则。将以下代码添加到app/Providers/AppServiceProvider.php方法中的boot()

Validator::extend('unique_with_id', function ($attribute, $value, $parameters, $validator) {
    // First we query for an entity in given table, where given field equals the request value
    $found = DB::table($parameters[0])
        ->where($parameters[1], $value)
        ->first();

    // then we add custom replacer so that it gives the user a verbose error

    $validator->addReplacer('unique_with_id', function ($message, $attribute, $rule, $parameters) use ($found) {
        // replace :entity placeholder with singularized table name and :id with duplicate entity's id
        return str_replace([':entity', ':id'], [str_singular($parameters[0]), $found->id], $message);
    });

    // finally return wether the entity was not found (the value IS unique)
    return !$found;
});

然后将以下验证消息添加到resources/lang/en/validation.php

'unique_with_id'=>'Same :entity exists with ID :id',

最后你可以使用

$validator = Validator::make($request->all(), [
    'short'         => 'required',
    'name'          => 'required|unique_with_id:type_event,name'
]);