Laravel Validation with Custom Error Messages

Published on Aug 31, 2019

Hello guys, today I’m going to show you how to display validation error custom messages. I’ll share three methods to change the error messages. Let’s start:

Table of Contents

  1. Set Error Messages in Controller
  2. Adding Error Messages in Language File
  3. Creating Custom Request

Step 1 : Set Error Messages in Controller

We can easily change custom error messages in the controller. This is a quick solution. Have a look at this method:

BookController.php
<?php

namespace App\Http\Controllers;

use App\Book;
use Illuminate\Http\Request;
use Validator;

class BookController extends Controller
{
    public function store(Request $request)
    {
        // validator
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'author' => 'required',
        ], [
            'name.required' => 'Please enter book name',
            'author.required' => 'Please enter book author',
        ]);

        // check validation
        if ($validator->fails()) {
            $response = [
                'success' => false,
                'message' => $validator->messages()
            ];
            return response()->json($response, 404);
        }

        // try to store the book
        try {
            $input = $request->all();
            Book::create($input);

            $success = true;
            $message = "Stored successful";
        } catch (\Illuminate\Database\QueryException $ex) {
            $success = false;
            $data = null;
            $message = $ex->getMessage();
        }

        // make response
        $response = [
            'success' => $success,
            'message' => $message
        ];

        // return response
        return response()->json($response, 200);
    }
}

Step 2 : Adding Error Messages in Language File

This is the last method. If we set custom error messages here, these will work in the whole project.

Open resources/lang/en/validation.php file and add custom errors with messages in the “custom” array. Here’s an example:

validation.php
'custom' => [
    'name' => [
        'required' => 'Please enter book name',
    ],
    'author' => [
        'required' => 'Please enter book author',
    ],
],

and the BookController looks like:

BookController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;
use Validator;

class BookController extends Controller
{
    public function store(Request $request)
    {
        // validator
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'author' => 'required',
        ]);

        // check validation
        if ($validator->fails()) {
            $response = [
                'success' => false,
                'message' => $validator->messages()
            ];
            return response()->json($response, 404);
        }

        // try to store the book
        try {
            $input = $request->all();
            Book::create($input);

            $success = true;
            $message = "Book successfully stored";
        } catch (\Illuminate\Database\QueryException $ex) {
            $success = false;
            $message = $ex->getMessage();
        }

        // make response
        $response = [
            'success' => $success,
            'message' => $message
        ];

        // return response
        return response()->json($response, 200);
    }
}

Step 3 : Creating Custom Request

By creating a custom request we can do this. To do this, we have to create a request. Let’s create a request by using this artisan command:

php artisan make:request BookFormRequest

Open the BookFormRequest from app\Http\Requests and paste this code:

BookFormRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BookFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'author' => 'required',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'name.required' => 'Please enter book name',
            'author.required' => 'Please enter book author',
        ];
    }
}

Let’s use this BookFormRequest request in our BookController.

BookController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\BookFormRequest;
use App\Book;

class BookController extends Controller
{
    public function store(BookFormRequest $request)
    {
        // try to store the book
        try {
            $input = $request->all();
            Book::create($input);

            $success = true;
            $message = "Book successfully stored";
        } catch (\Illuminate\Database\QueryException $ex) {
            $success = false;
            $message = $ex->getMessage();
        }

        // make response
        $response = [
            'success' => $success,
            'message' => $message
        ];

        // return response
        return response()->json($response, 200);
    }
}

Note: To get the response from the custom request, we have to set header Accept: application/json.

The tutorial is over. You can choose any method. Thank you. ?

Comments (0)