我将验证器用作
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'phone' => 'required|max:10|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
这将以以下格式给出响应:
{
"error": {
"phone": [
"The phone has already been taken."
],
"email": [
"The email has already been taken."
]
}
}
我希望回复
{
"error": 1,
"error_msg": "The phone has already been taken."
}
只有一种错误应该以上述格式显示。
答案 0 :(得分:0)
为使验证在第一次验证失败后停止,laravel使用bail
检查this。因此规则将是这样
$validator = Validator::make($request->all(), [
'name' => 'bail|required|max:255',
'phone' => 'bail|required|max:10|unique:users',
'email' => 'bail|required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
对于格式化错误消息,您需要在响应中进行一些更改
if ($validator->fails()) {
return response()->json(['error'=> 1, 'error_msg' => $validator->errors()->first()], 400);
}
您可以创建一个中心位置来呈现验证错误,以使其在整个应用程序中保持一致的验证响应格式。
希望这可能对您有帮助
答案 1 :(得分:0)
使用Form Request进行验证:
class CreateUserRequest extends FormRequest {
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|max:255',
'phone' => 'required|max:10|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
];
}
public function messages()
{
return [
'phone.unique' => 'The phone has already been taken.',
'email.unique' => 'The email has already been taken.',
];
}
}
然后在您的控制器中使用它:
public function create(CreateUserRequest $request)
{
$user = User::create($request->all());
return response()->json(['user'=>$user]);
}
这会在运行create方法之前进行验证,并在json响应中为您返回验证错误消息。
我建议不要更改响应的格式,而应适应laravel返回的格式,因为它始终是统一的形状。这样,您的客户可以期望一致的api响应。
此外,验证失败应该是422
状态,而不是用于身份验证的401
。