For Laravel 8
go to your \app\Exceptions\Handler.php
and override invalidJson
method like this:
// Add this line at the top of the class
use Illuminate\Validation\ValidationException;
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
// You can return json response with your custom form
return response()->json([
'success' => false,
'data' => [
'code' => $exception->status,
'message' => $exception->getMessage(),
'errors' => $exception->errors()
]
], $exception->status);
}
Response Sample:
{
"success": false,
"data": {
"code": 422,
"message": "The given data was invalid.",
"errors": {
"password": [
"The password field is required."
]
}
}
}
The original method was:
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}
Response Sample:
{
"message": "The given data was invalid.",
"errors": {
"password": [
"The password field is required."
]
}
}
Note that unauthenticated
response is in separate method, so you can override it as well
/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
// Here you can change the form of the json response
? response()->json(['message' => $exception->getMessage()], 401) // <-
: redirect()->guest($exception->redirectTo() ?? route('login'));
}
Response
class and call it instead of the "right" one? It's that it? – Manet