Laravel中CustomRequest验证失败时自定义message字段内容
当然可以!这在Laravel里非常容易实现
你只需要在你的CustomRequest类中重写response方法,就能完全自定义验证失败时返回的响应内容。具体步骤如下:
- 打开你的
CustomRequest文件(一般在app/Http/Requests目录下) - 添加下面的方法到类中:
/** * Get the response for a failed validation. * * @param array<string, array<string>> $errors * @return \Illuminate\Http\JsonResponse */ public function response(array $errors) { return response()->json([ 'message' => 'custom message only for this CustomRequest fail.', 'errors' => $errors ], 422); }
这样当这个请求类的验证失败时,就会返回你想要的自定义message,同时保留原来的errors结构。
另外还有一种方式,如果你想通过抛出异常的方式来处理,可以重写failedValidation方法:
use Illuminate\Validation\ValidationException; /** * Handle a failed validation attempt. * * @param \Illuminate\Contracts\Validation\Validator $validator * @return void * * @throws \Illuminate\Validation\ValidationException */ protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { $exception = ValidationException::withMessages($validator->errors()->toArray()); // 自定义响应内容 $exception->response = response()->json([ 'message' => 'custom message only for this CustomRequest fail.', 'errors' => $validator->errors()->toArray() ], 422); throw $exception; }
两种方式都能达到你的需求,第一种重写response方法更简洁直接,推荐使用。
内容的提问来源于stack exchange,提问作者Bolek Lolek
相关产品推荐
相关产品推荐

