Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I set custom validation error messages from a controller, in Laravel 8?

I am working on a registration form consisting with Laravel 8 and Sanctum.

I have this piece of code in the AuthController to validate the form fields:

public function register(Request $request) {
    $fields = $request->validate([
        'first_name' => 'required|string,',
        'last_name' => 'required|string',
        'email' => 'required|string|unique:users,email',
        'password' => 'required|string|confirmed',
        'accept' => 'accepted',
    ]);

    // More code here

}

I want to display more user-friendly validation error messages.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Rather than changing the validation.php file (resources\lang\en\validation.php), I want to change the set them for the registration form only, in the method above.

The problem

As someone that has used Codeigniter for a long time, I had, in Codeigniter, the posibility to do just that:

  $this->form_validation->set_rules('first_name', 'First name', 'required', array('required' => 'The "First name" field is required'));

I was unable to do something similar in Laravel 8.

How do I get the desired result in Laravel 8?

>Solution :

Maybe this can work for ya.

    $rules = [
        'first_name' => 'required|string,',
        'last_name' => 'required|string',
        'email' => 'required|string|unique:users,email',
        'password' => 'required|string|confirmed',
        'accept' => 'accepted'
    ];

    $customMessages = [
        'required' => 'The :attribute field is required.'
    ];

    $this->validate($request, $rules, $customMessages);

Also check out the laravel customizing error messages documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading