logo
podcast Podcast
get help Get Unstuck

How to customize the message for enum validation

It wasn't completely obvious to me

Joel Clermont
Joel Clermont
2024-07-29

In Laravel, most of the rules are available as string based rules, like string or max, but some rules are only available as classes, like Rule::enum().

While I normally prefer to stick with default validation messages, recently I was on a project where they wanted to customize the messages to conform to their existing style.

No problem at all with the string based rules. You can do something like this inside the form request class:

public function messages(): array
{
    return [
        'field_name.rule_name' => 'Your custom message here',
    ];
}

But when I tried field_name.enum for the class-based enum rule, it didn't use my custom message.

I saw nothing in the docs about this, but digging into Laravel's source code (hooray, open source!), I found it was looking for the fully qualified class name of the rule instead:

use Illuminate\Validation\Rules\Enum;

public function messages(): array
{
    return [
        sprintf('field_name.%s', Enum::class) => 'Your custom message here',
    ];
}

I could have shoved the full class name literal in my string, but we really like using sprintf for readable string formatting.

Here to help,

Joel

P.S. Aaron and I share a lot of what we know about validation in Mastering Laravel Validation Rules. Buy a copy to level up your knowledge and support us.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.