如何使用Laravel保释验证?
How to use Laravel Bail validation?
我在每个验证请求上使用 Bail
规则,我希望它在第一次验证异常时停止并且不验证其他请求参数。但它会验证所有输入数据。
MyController.php
public function update(Request $request)
{
$user = auth()->user();
$request->validate([
'name' => ['bail','string'],
'email' => ['bail','email', Rule::unique('users')->ignore($user->id)],
]);
$user->update(request()->only('name', 'email'));
return response()->json($user);
}
请求数据:
{name: "example", email: "example@domain.com"}
响应:
{
"message": "The given data was invalid.",
"errors": {
"name": [
"The name field is required."
],
"email": [
"The email has already been taken."
]
}
}
有什么问题?
bail
验证规则适用于 "multi-rule" 属性 。它不会停止运行对其他属性的验证。来自 the documentation:
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required',
]);
If the unique
rule on the title attribute fails, the max
rule will not be checked.
我在每个验证请求上使用 Bail
规则,我希望它在第一次验证异常时停止并且不验证其他请求参数。但它会验证所有输入数据。
MyController.php
public function update(Request $request)
{
$user = auth()->user();
$request->validate([
'name' => ['bail','string'],
'email' => ['bail','email', Rule::unique('users')->ignore($user->id)],
]);
$user->update(request()->only('name', 'email'));
return response()->json($user);
}
请求数据:
{name: "example", email: "example@domain.com"}
响应:
{
"message": "The given data was invalid.",
"errors": {
"name": [
"The name field is required."
],
"email": [
"The email has already been taken."
]
}
}
有什么问题?
bail
验证规则适用于 "multi-rule" 属性 。它不会停止运行对其他属性的验证。来自 the documentation:
$request->validate([
'title' => 'bail|required|unique:posts|max:255',
'body' => 'required',
]);
If the
unique
rule on the title attribute fails, themax
rule will not be checked.