How to customize laravel request validation response to JSON

In every application, data validation before executing further logic is required. Laravel provides an easy way to implement data or user input validation using its validator methods.

Laravel has a special request class concept for validation. Which separate validation logic and actual logic. But sometimes working with Laravel request validation class, we need to return validation errors in JSON format instead of error bag. It’s commonly used in APIs

Let’s take an example to return JSON data for validation request error or customize error response. Here, we will take user input and validate it using the Laravel request method.

To create a request class, open the terminal and enter the below command:

php artisan make:request UserStoreRequest

It will create a new file under the App\Http\Requests directory. Open the file and modify it as below:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class UserStoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name'              =>  'required',
            'email'             =>  'required|email',
            'password'          =>  'required|min:8',
            'c_password'        =>  'required|min:8|same:password',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            reponse()->json([
                'message'   =>  'Data Validation Failed',
                'errors'    =>  $validator->errors()
            ])''
        );
    }
}

Here, we have added some common validation rules like the name field is required, the email field is also required and must be email and password, and the confirm password must be the same.

Here, we have added failedValidation() method to handle error response. Normally if validation fails Laravel handles it as regular but this method will override the default error response logic as per our requirement.

Here, we have passed the validator instance as a parameter to get validation errors. It will throw an HTTP response exception with our custom response format. In this case, which is JSON.

Conclusion

This article created a validation request class for user inputs, and if validation fails it will return JSON containing errors.