How to set custom validation message in laravel?

by filiberto , in category: PHP Frameworks , 5 months ago

How to set custom validation message in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 5 months ago

@filiberto 

In Laravel, you can set a custom validation message by using the messages() method in your controller or form request class.


Option 1: Using the messages() method in the controller

  1. First, create a new rule in your controller using the Validator facade. For example: use IlluminateSupportFacadesValidator; public function store(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required|min:8', ]); if ($validator->fails()) { return redirect('form') ->withErrors($validator) ->withInput(); } // Validation passed, continue with the rest of your code }
  2. To set custom validation messages, add the messages() method after defining the rules. For example: public function store(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required|min:8', ]); $validator->messages()->add([ 'email.required' => 'The email field is required.', 'password.min' => 'The password must be at least 8 characters.', ]); if ($validator->fails()) { return redirect('form') ->withErrors($validator) ->withInput(); } // Validation passed, continue with the rest of your code }


Option 2: Using a form request class

  1. Create a new form request class using the make:request Artisan command. For example: php artisan make:request MyFormRequest
  2. Open the newly created MyFormRequest.php file and update the rules() method with your validation rules. For example: public function rules() { return [ 'email' => 'required|email', 'password' => 'required|min:8', ]; }
  3. To set custom validation messages, add the messages() method in the MyFormRequest class. For example: public function messages() { return [ 'email.required' => 'The email field is required.', 'password.min' => 'The password must be at least 8 characters.', ]; }
  4. In your controller, type-hint the MyFormRequest class in your store() method. For example: use AppHttpRequestsMyFormRequest; public function store(MyFormRequest $request) { // Validation passed, continue with the rest of your code }


By following these steps, you can set custom validation messages in Laravel.