How to return json from laravel form request validation errors

Recently I have been using Laravel Form Request Validation instead of using inline validation. I find it much nicer to break things out into their own classes as much as possible so I was pleased when this made its way into the core framework.

If you are like me and you cannot get out of the habit of writing inline validation then don’t worry because the wonderful Jason McCreary has added an awesome feature to the Laravel Code Fixer Shift to convert inline controller validation to Form Requests.

When using Form Requests with API’s you will notice that if you hit an API route where the validation fails it will throw you to a 404 view.

My solution is to make my own FormRequest class which I put in the root API namespace namespace App\Http\Requests\Api;

<?php
namespace App\Http\Requests\Api;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
abstract class FormRequest extends LaravelFormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    abstract public function rules();
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    abstract public function authorize();
    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        $errors = (new ValidationException($validator))->errors();
        throw new HttpResponseException(
            response()->json(['errors' => $errors], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );
    }
}

view rawFormRequest.php hosted with by GitHub

So your SearchController which uses the SearchRequest instead of the default Request stays the same.

We just update the SearchRequest to use our custom FormRequest and not the default and we will get a nice JSON response when we have validation errors.

<?php

namespace App\Http\Requests\Api\Flight;

use Illuminate\Foundation\Http\FormRequest;

class SearchRequest extends FormRequest
{
    ...
}

So now our class will extend our own custom class

<?php

namespace App\Http\Requests\Api\Flight;

use App\Http\Requests\Api\FormRequest;

class SearchRequest extends FormRequest
{
    ...
}

So now when we hit the API endpoint we will get this

Refer: https://jamesmills.co.uk/2019/06/05/how-to-return-json-from-laravel-form-request-validation-errors/