Reputation: 1063
Developing with Laravel 5.4 I am trying the example from Laravel documentation:
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function($attribute, $value, $fail) {
if ($value === 'foo') {
return $fail($attribute.' is invalid.');
}
},
],
]);
I am getting this error:
Object of class Closure could not be converted to string
Why?
Upvotes: 5
Views: 5491
Reputation: 2499
In Laravel 5.4 this does not work. You need to update to Laravel 5.6, or at least have "illuminate/validation" version 5.6
Upvotes: 3
Reputation: 9749
In 5.4 if you wan't a closure you can pass it after the validation rules, like this:
$validator = Validator::make($request->all(), [
'title' => ['required', 'max:255'],
]);
$validator->after(function ($validator) {
if ($request->get('field') === 'foo') {
$validator->errors()->add('field', 'Field is invalid.');
}
});
if ($validator->fails()) {
//
}
Upvotes: 4