Laravel Validation: Specify Attribute Names for Error Messages

Laravel validation system is great, including auto-populating error messages. But what if you want to override the names of the :attribute parameter values? Here's a simple example.

Typical example of validation rules array:

$rules = [
    'first_name' => 'required',
    'last_name' => 'required',
];

Then, if validaton fails with first_name being empty, automatic error message will say this: The first name field is required.

As you can see, first_name is automatically transformed to first name, with a space. This is great for web-based project to explain to a human, what is missing. But for APIs and similar cases, it's important to provide specifically that exact attribute, in its original name, so it should remain unchanged, as first_name.

We can specify that in one of the parameters for validation called attributes(). In fact, we can override those :parameter values to be anything we want.

Here's an example with Validator class:

$rules = [
    'first_name' => 'required|bail',
    'last_name' => 'required',
];

$messages = [
    'required' => 'please specify :attribute option',
];

$attributes = [
    'first_name' => 'first_name',
    'last_name' => 'last_name',
];

$validator = Validator::make($request->all(), $rules, $messages, $attributes);

Look at that $attributes array, and we're passing it as the 4th parameter to Validator::make(). I know it looks awkward to assign the array keys to the same values, but it works.

If you are using FormRequest classes for validation, then all you need to do is add method attributes() to the class, with the same values:

public function attributes()
{
    return [
        'first_name' => 'first_name',
        'last_name' => 'last_name',
    ];
}

Read more about validation in official Laravel documentation.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord