How to use custom validation message in laravel?

by lindsey.homenick , in category: PHP Frameworks , 4 months ago

How to use custom validation message in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 4 months ago

@lindsey.homenick 

To use custom validation messages in Laravel, you can define your custom messages in the validation rule either in the Controller or in the validation request class.

  1. Define custom messages in the Controller:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public function store(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required|min:6',
    ], [
        'email.required' => 'Please enter an email address',
        'email.email' => 'Please enter a valid email address',
        'password.required' => 'Please enter a password',
        'password.min' => 'Password must be at least 6 characters',
    ]);
}


  1. Define custom messages in the Validation Request Class: First, create a new validation request using the following artisan command:
1
php artisan make:request StoreUserRequest


Then, open the newly created StoreUserRequest file and define custom messages in the messages() method:

1
2
3
4
5
6
7
8
9
public function messages()
{
    return [
        'email.required' => 'Please enter an email address',
        'email.email' => 'Please enter a valid email address',
        'password.required' => 'Please enter a password',
        'password.min' => 'Password must be at least 6 characters',
    ];
}


Remember to import the newly created validation request class in your Controller and use it in the store method:

1
2
3
4
5
6
use AppHttpRequestsStoreUserRequest;

public function store(StoreUserRequest $request)
{
    // Validation passes if the input data is valid
}


By using custom validation messages, you can provide more user-friendly and informative error messages when validation fails in your Laravel application.