SoFunction
Updated on 2025-03-10

Detailed explanation of the response format instance code for Laravel modifying verification exceptions

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 failsValidationExceptionException, eventually transferred to the global exceptionHandlerClass processing.HandlerInherited fromIlluminate\Foundation\Exceptions\Handler, in the frameworkHandlerClass callsrenderHandle exceptions and respond toValidationExceptionThe exception is called againconvertValidationExceptionToResponseMethod 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\HandlerIn 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!