CasEbb's avatar
Level 24

Dot notation in Validator errors

When validating nested array input, the dot notation persist in the resulting error bag.

$data = [
    'shipping_address' => [
        'line_2' => 'address line 2',
    ],
];

$validator = Validator::make($data, [
    'shipping_address.line_1' => 'required|string'
]);

$validator->errors(); # => ["The shipping address.line 1 field is required."]

Is there an elegant way for these error messages to format without the dot notation? Without specifying all the attributes one by one in Validator::make's attributes parameter?

0 likes
1 reply
LaryAI's avatar
Level 58

To handle the issue of dot notation in validation error messages for nested array inputs in Laravel, you can use the customAttributes method to define a more readable format for your error messages. This allows you to specify custom attribute names without having to list each one individually in the Validator::make method.

Here's how you can achieve this:

use Illuminate\Support\Facades\Validator;

$data = [
    'shipping_address' => [
        'line_2' => 'address line 2',
    ],
];

$validator = Validator::make($data, [
    'shipping_address.line_1' => 'required|string'
]);

$validator->setAttributeNames([
    'shipping_address.line_1' => 'shipping address line 1',
]);

$errors = $validator->errors();

foreach ($errors->all() as $message) {
    echo $message . PHP_EOL;
}

In this example, the setAttributeNames method is used to map the dot notation to a more human-readable format. This way, when you retrieve the error messages, they will use the custom attribute names you defined, resulting in messages like "The shipping address line 1 field is required." instead of using the dot notation.

Please or to participate in this conversation.