If any of this rules failed, it'll be stop
And it’s gonna be the same here, isn’t it?
CodePudding user response:
As per docs https://laravel.com/docs/9.x/validation#stopping-on-first-validation-failure:
Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute.
Maybe it's useless for simple validation, but you may have a validation closure
or a unique
validation that you want to avoid if the first validation fails.
Let's say you have a validation like this
$request->validate([
'title' => 'max:255|unique:posts'
]);
In case of not using bail
, the unique:posts
will be hitting your database looking for a unique post despite max:255
validation failed.
Or having a closure validation:
$request->validate([
'title' => [
'max:255',
function ($attribute, $value, $fail) {
$posts = Post::where('title', 'LIKE', $value)->count();
if ($posts > 0) {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
Imagine having 500K posts, and looking for a post with the same title despite max:255
fails.
CodePudding user response:
Buddy Just check out the error message and you will find that only one validation condition is checked when "bail" is provided
//when "bail" is not provided
$request->validate([
'foo' => 'required|min:5|in:er,err,erro,error'
]);
/*
#messages: array:1 [
"foo" => array:2 [
0 => "The foo must be at least 5 characters."
1 => "The selected foo is invalid."
]
]
*/
//when "bail" is provided
$request->validate([
'foo' => 'bail|required|min:5|in:er,err,erro,error'
]);
/*
#messages: array:1 [
"foo" => array:1 [
0 => "The foo must be at least 5 characters."
]
]
*/