Custom Validation Attributes in Laravel

Published 1st May 2018

Recently, I was working on some Laravel validation that used the array syntax to validate fields. For example:

$validator = Validator::make($request->all(), [
    'database_options.name' => 'required|min:3|max:64',
]);

However, in this case the error message that is returned looks like this:

The database options.name field is required.

Not ideal. The Laravel docs cover how to customize the error messages for rules but not for the attribute names themselves.

It turns out there is a simple solution to this issue. You can override an attributes name by passing in an array of attribute names as the fourth parameter of the Validator::make method.

$attributes = [
    'database_options.name' => 'database name',
];

$validator = Validator::make($request->all(), [
    'database_options.name' => 'required|min:3|max:64',
], [], $attributes);

Now the error message should appear like this:

The database name field is required.