Laravel: Customizing the field names in validation error messages cover image

Laravel: Customizing the field names in validation error messages

Sam Ciaramilaro • August 15, 2022

code laravel

In working with API request validation in Laravel, I am frequently writing FormRequest classes. Usually, the input data is provided using "snake_case" field names. However, when there are validation errors, the field names returned in the default error messages do not exactly match the original field names.

For example, consider the following FormRequest class:

// FormRequest class

public function rules()
{
    return [
        'last_name' => 'required'
    ];
}

// Error message generated. The "last_name" field is split into separate 
// words, instead of "first_name" as was provided to the validator.
"The last name field is required."

There are two ways to solve this. One approach is to specify custom error messages, with the input field written in the correct/desired format you want displayed in the message.

// in FormRequest
public function messages()
{
    return [
        'last_name.required' => 'The last_name field is required.'
    ];
}

This is fine for a single rule or two, but what if there are multiple fields, each having multiple validation rules? Using this approach, you'd have to write a custom error message for each field/rule combination. This can quickly add up to a lot of messages being written.

public function rules()
{
    return [
        'last_name' => [
            'required',
            'min:2',
            'max:255',
        ],
        'first_name' => [
            'required',
            'min:2',
            'max:255',
        ],
    ];
}

// Custom error messages for each field/rule combination.
public function messages()
{
    return [
        'last_name.required' => 'The last_name field is required.',
        'last_name.min' => 'The last_name must be at least 3 characters.',
        'last_name.max' => 'The last_name must not be greater than 255 characters',
        'first_name.required' => 'The last_name field is required.',
        'first_name.min' => 'The first_name must be at least 3 characters.',
        'first_name.max' => 'The first_name must not be greater than 255 characters',
    ];
}

As you can see, that's a lot of boilerplate just to correct the field name in the error messages. Not very sustainable in the long run.

In this instance, a better approach would be to simply customize the validation attributes using the attributes() method.

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

// Default error message returned.
"The last_name field is required."

That's it. That all it takes. This way, "last_name" would be output for all error messages, and you can avoid writing custom error messages.

For more usage information and options, see Customizing The Validation Attributes in the official Laravel documentation.