Laravel modify the response format of verification exception

Posted May 25, 20202 min read

The default format of Laravel after failing to pass the verification is as follows. Sometimes this format does not meet your own requirements, and you need to modify the format.

//status 422
{
    "message":"The given data was invalid.",
    "errors":{
        "url":[
            "url invalid format"
       ]
    }
}

When Request verification fails, a ValidationException exception will be thrown, which will eventually be handled by the global exception handler class. Handler inherits from Illuminate \ Foundation \ Exceptions \ Handler. The Handler class in the framework calls render to handle the exception and responds. For the ValidationException exception, the convertValidationExceptionToResponse method is called 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() distinguishes between ajax requests and form requests, and then handles them separately.

protected function invalidJson($request, ValidationException $exception)
{
    return response()-> json([
        'message' => $exception-> getMessage(),
        'errors' => $exception-> errors(),
   ], $exception-> status);
}

Traced to invalidJson() and found that he is the method used to handle the parameter verification exception response format. In the App \ Exceptions \ Handler class, simply override theinvalidJson()method.

protected function invalidJson($request, ValidationException $exception)
{
    return response()-> json([
        'code' => 0,
        'data' => $exception-> errors(),
   ], $exception-> status);
}

Finally, the format of the response to verification failure is as follows

//status 422
{
    "code":0,
    "data":{
        "url":[
            "url invalid format"
       ]
    }
}