How to set custom response for selected Request class in Laravel 5.5 How to set custom response for selected Request class in Laravel 5.5 laravel laravel

How to set custom response for selected Request class in Laravel 5.5


If you want to customize validation response only for selected Request class, you need to add failedValidation() message to this class:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator){    $response = new JsonResponse(['data' => [],              'meta' => [                'message' => 'The given data is invalid',                 'errors' => $validator->errors()             ]], 422);    throw new \Illuminate\Validation\ValidationException($validator, $response);}

This way you don't need to change anything in Handler and have this custom response only for this single class.

And if you want to change format globally for all responses you should add to app\Exceptions\Handler.php file the following method:

protected function invalidJson($request, ValidationException $exception){    return response()->json([             'data' => [],              'meta' => [                'message' => 'The given data is invalid',                 'errors' => $exception->errors()             ]             ], $exception->status);}

You can read about this also in Upgrade guide in Exception Format section