Laravel 8 set custom messages in form request validation

How to set custom error message using laravel Form Request Validation in Laravel 8


In this article, you will be learning how to set custom error messages using form request validation in laravel 8.

So guys, you will already be knowing about how to make Form Request Validation in Laravel and now, you want to set a custom messages to show about the errors as per your requirement. 

So, we will be using an example of Student Data:


Step 1: Create Request Class (Form Request Validation in Laravel) by following command: 

$ php artisan make:request StudentFormRequest


Step 2: After successfully create Request Class, paste the below code:

custom message are set in messages() function below

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StudentFormRequest 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()
    {
        $rules = [
            'fullname' => [
                'required',
                'string',
                'max:191',
            ],
            'email' => [
                'required',
                'email',
                'max:191',
                'unique:students,email',
            ],
            'phone' => [
                'required',
                'digits:10',
            ],
            'course' => [
                'required',
                'string',
                'max:191',
            ],
        ];

        return $rules;
    }

    public function messages()
    {
        return [
            'fullname.required' => 'Please enter your fullname',
            'email.required' => 'Please enter your email id',
            'email.email' => 'Please enter valid email id',
            'phone.required' => 'Please enter your phone no',
            'course.required' => 'Please enter your course',
        ];
    }
}


Thanks for reading.