Laravel 中带保释和不带保释的验证规则有什么区别?
What's the difference between validation rules with bail and without in Laravel?
If any of this rules failed, it'll be stop
And it’s gonna be the same here, isn’t it?
根据文档 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.
也许它对简单验证没有用,但如果第一次验证失败,您可能希望避免验证 closure
或 unique
验证。
假设您有这样的验证
$request->validate([
'title' => 'max:255|unique:posts'
]);
如果不使用 bail
,尽管 max:255
验证失败,unique:posts
仍会访问您的数据库以寻找唯一的 post。
或进行闭包验证:
$request->validate([
'title' => [
'max:255',
function ($attribute, $value, $fail) {
$posts = Post::where('title', 'LIKE', $value)->count();
if ($posts > 0) {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
想象一下,有 500K posts,尽管 max:255
失败,但寻找具有相同标题的 post。
小伙伴看看错误信息,你会发现提供“保释”时只检查了一个验证条件
//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."
]
]
*/
If any of this rules failed, it'll be stop
And it’s gonna be the same here, isn’t it?
根据文档 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.
也许它对简单验证没有用,但如果第一次验证失败,您可能希望避免验证 closure
或 unique
验证。
假设您有这样的验证
$request->validate([
'title' => 'max:255|unique:posts'
]);
如果不使用 bail
,尽管 max:255
验证失败,unique:posts
仍会访问您的数据库以寻找唯一的 post。
或进行闭包验证:
$request->validate([
'title' => [
'max:255',
function ($attribute, $value, $fail) {
$posts = Post::where('title', 'LIKE', $value)->count();
if ($posts > 0) {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
想象一下,有 500K posts,尽管 max:255
失败,但寻找具有相同标题的 post。
小伙伴看看错误信息,你会发现提供“保释”时只检查了一个验证条件
//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."
]
]
*/