Search code examples
phplaravellaravel-validation

LARAVEL 5.3 - Validator custom messages ignored


I got in my login post method:

$validator = Validator::make(
    $request->all(), 
    [
        'user' => 'required',
        'password' => 'required'
    ],[
        'user' => 'Username is required',
        'password' => 'Password is required'
    ]
);

But unless I change 'password' => 'Password is required' to 'password.required' => 'Password is required', the custom message is ignored and the default is sent to the view.

Do I really have to specify the rule in the message or am I doing something wrong?


Solution

  • Laravel looks first on custom messages and if it is not able to find one then it falls back to normal validation messages.

    'password' => 'Password is required' is not for required validation your have set. so the default message is working. You have to write custom message on specific error type.

    Example: password is required and should also be integer then

    $validator = \Validator::make(
            $request->all(), 
            [
                'password' => 'required|integer'
            ],[
                'password.integer' => 'Password needs to be interger',
                'password.required' => 'Password is required'
            ]
    );
    

    Note: you can also set your custom messages in validation.php file and add your messages in custom array. You will be able to use your custom messages globally then.

    'custom' => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ]