The response format after Laravel's default verification fails, is as follows. Sometimes this format does not meet its own requirements and needs to be modified.
// status 422 { "message":"The given data was invalid.", "errors":{ "url":[ "url invalid format" ] } }
Thrown when Request verification failsValidationException
Exception, eventually transferred to the global exceptionHandler
Class processing.Handler
Inherited fromIlluminate\Foundation\Exceptions\Handler
, in the frameworkHandler
Class callsrender
Handle exceptions and respond toValidationException
The exception is called againconvertValidationExceptionToResponse
Method to handle.Code
protected function convertValidationExceptionToResponse(ValidationException $e, $request) { if ($e->response) { return $e->response; } return $request->expectsJson() ? $this->invalidJson($request, $e) : $this->invalid($request, $e); }
expectsJson()
Distinguish whether it is an ajax request or a form request, and then process it separately.
protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'message' => $exception->getMessage(), 'errors' => $exception->errors(), ], $exception->status); }
Tracked toinvalidJson()
, found that it is the method used to handle parameters to verify the exception response format. existApp\Exceptions\Handler
In class, rewriteinvalidJson()
Just the method.
protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'code' => 0, 'data' => $exception->errors(), ], $exception->status); }
Finally, the response format for verification failure is as follows
// status 422 { "code": 0, "data":{ "url":[ "url invalid format" ] } }
Summarize
This is the introduction to this article about the detailed explanation of the code for modifying the response format of Laravel verification exceptions. For more related contents of Laravel exception response format, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!