当我在Laravel中使用Validator类时,我能够为我的ajax-捕获这样的错误
$validator= Validator::make($request->all(),[
'name' => 'required',
'email' => 'required|email',
'age' => 'required|min:3',
'number' => 'required|numeric',
]);
if($validator->fails()){
return response()->json([
'status'=> 400,
'errors'=>$validator->messages(),
]);
}
但是,如果不使用Validator类或使用以下代码-,我如何捕捉错误消息
$request->validate([
'name' => 'required',
'email' => 'required|email',
'age' => 'required|min:3',
'number' => 'required|numeric',
]);
我想将错误消息存储在Controller中的一个变量中,这样我就可以将它们发送到JSON
https://github.com/laravel/framework/blob/9.x/src/Illuminate/Validation/ValidationException.php
try {
$request->validate([
'name' => 'required',
'email' => 'required|email',
'age' => 'required|min:3',
'number' => 'required|numeric',
]);
} catch (ValidationException $e) {
if($request->wantsJson()) {
return response()->json([
'status' => 400,
'errors' => $e->errors(),
]);
}
throw $e; // return to laravel default handler
}
使用刀片视图中的$errors var显示错误