How to return a response for failed validation in Laravel in new ways?

Using Laravel Form Requests in a controller and on validation fail, the Form Request will redirect back with the errors variable. We can make a failed validation return a custom error response. There are some new ways to return a JSON response for failed validation.

Custom FormRequest class

We can create a custom FormRequest class to return a custom error response when the data is invalid.

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;

class FormRequest extends \Illuminate\Foundation\Http\FormRequest
{
    protected function failedValidation(Validator $validator)
    {
        if ($this->expectsJson()) {
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(
                response()->json(['data' => $errors], 422)
            );
        }

        parent::failedValidation($validator);
    }
}

You can add this class to the app/Http/Requests directory. This is a tried and tested solution that works in Laravel 6.x.

Adding an exception handler for failed validation

Another way is to use the Illuminate\Http\Exceptions\HttpResponseException to handle failed validation exceptions.

You can add a handler file to the app/http/exceptions directory. The code snipper below renders the function with the following lines.

if ($exception instanceof \Illuminate\Validation\ValidationException) 
{ 
 return new JsonResponse($exception->errors(), 422); 
}

The two new ways above return custom JSON responses on error or invalid data entry. The previous method was to extend the FormRequest and override the response method. But this has stopped working with updates to 5.5.

The ‘old’ method was used to override the failedValidation method and put the response into a ValidationException. However, in that case, a ReflectionException was thrown because the Request class is not found.

The above two are correct ways to create a custom response in laravel 6.x?