1
votes

Is there a simple way to replace the input name in Laravel's validation messages with for example a label?

Right now message is like:

The usrRoleId field is required.

I know there are two options:

  1. Change input names to more readable.

  2. Write EACH message in the validation request to look like this: User Role is required.

I'm looking for something more automatic - like defining a string once and using it every time such field name is used.

1

1 Answers

1
votes

Yes you can and it's actually quite easy. You can specify a custom name for a given attribute in your resources/lang/en/validation.php file under the attributes key:

'attributes' => [
    'usrRoleId' => 'User Role'
],

And now anywhere you have usrRoleId for the :attribute inside a validator message, it will be replaced with User Role. So instead of:

The usrRoleId field is required.

You'll get the nice:

The User Role field is required.


If you want to have a whole custom message not only a custom attribute name for when the usrRoleId is required, then you can add an entry for that user the custom key in the same file. So adding this:

'custom' => [
    'usrRoleId' => [
        'required' => 'User Role is required',
    ],
],

Will use that custom message but without an :attribute placeholder. If you want to use the placeholder you can leave the attributes mapping I described above:

'custom' => [
    'usrRoleId' => [
        'required' => ':attribute is required',
    ],
],

And you'll still get your custom message but with the mapped attribute name:

User Role is required.