1

I am working on a registration form 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.

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?
1
  • 1
    You can optionally supply messages as the second argument, and optionally set attributes in the third argument. This is the facade method: \Illuminate\Contracts\Validation\Validator make(array $data, array $rules, array $messages = [], array $customAttributes = []) Commented Jan 17, 2022 at 12:10

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How do I target each/any field with a custom message? Like, for instance, "Looks like you forgot to tell us your name".
It would be better for you if you find it by yourself, but I'll give it to ya: 'first_name.required' => 'Looks like you forgot to tell us your name'
1

The validate function excepts 3 parameters. A) request, B) the rules, C) Custome Messages.

$this->validate($request, $rules, $customMessages); It means define your custom Message Array by key value. Key is the rulename like require. For example:

[
    'required' => 'The :attribute is really,really, really required if you use Login!'
    'email.required' => 'Without email you dont come in ;-)'
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.