Php L5.3-验证程序-在';独特的';硅触发
我正在使用Php L5.3-验证程序-在';独特的';硅触发,php,laravel,validation,Php,Laravel,Validation,我正在使用Validator验证输入: $validator = Validator::make($request->all(), [ 'short' => 'required', 'name' => 'required|unique:type_event,name' ]); if ($validator->fails()) { // fails validation } 启动unique检查时,是否有方法接收
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();
谢谢。首先,您需要自定义验证规则。将以下代码添加到
boot()
方法中的app/Providers/AppServiceProvider.php
:
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'
]);
首先,您需要一个自定义的验证规则。将以下代码添加到
boot()
方法中的app/Providers/AppServiceProvider.php
:
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'
]);
您可以打印
$validator->errors()
输出并粘贴到此处吗?唯一验证器仅使用提供的属性执行计数查询,因此您必须自己执行额外的查询。您可以打印$validator->errors()吗
输出并粘贴到此处?唯一验证器仅使用提供的属性执行计数查询,因此您必须自己执行额外的查询。