How i can return a customized response in a FormRequest class in Laravel 5.5?

For this Need to override failedValidation() function in your Request file.

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(response()->json([
      'errors' => $validator->errors(),
      'status' => false
    ], 422));
}

To make it work use these namespaces:

For laravel 5.4 and above:

 use Illuminate\Contracts\Validation\Validator;

 use Illuminate\Http\Exceptions\HttpResponseException;

description here

Below laravel 5.4:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exception\HttpResponseException;

description here


You have to override the failedValidation() method and issue the exception with the response what you want. So, you need to use Illuminate\Contracts\Validation\Validator and Illuminate\Http\Exceptions\HttpResponseException in the RequestForm class, and override the failedValidation() method:

protected function failedValidation(Validator $validator) { 
        throw new HttpResponseException(response()->json($validator->errors()->all(), 422)); 
}

In my case i using Laravel 7 and change a little:

//add depences
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;

//override this method in your FormRequest
protected function failedValidation(Validator $validator){
  throw new HttpResponseException(response()->json($validator->errors(), 422)); 
}