Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Validating against a subset of enum values

With conditional logic

Joel Clermont
Joel Clermont
2025-07-15

From our daily Laravel tips email. Get the next one in your inbox.

Today starts a multi-day run of validation tips pulled from the just-released 3rd edition of the Mastering Laravel Validation Rules book. Enjoy!

Laravel provides the Rule::enum() method to make it easy to validate data against valid values within a PHP enum.

You can also chain on only() or except() if you want to validate against a subset of the enum values.

But what if you need some conditional logic to decide which subset you want to validate against?

Rule::enum() also supports the Conditionable trait, which gives us a when() method.

Suppose we are letting someone schedule a meeting, but we have a strict "no meeting on Monday mornings" policy? Here's how you can easily express that:

$rules = [
    'time_period' => Rule::enum(TimeStartPeriod::class)
        ->when(
            Carbon::parse($this->get('meeting_date'))->isMonday(),
            fn($rule) => $rule->except([TimeStartPeriod::MORNING])
        ),
];

In the past, we'd have to write a custom validation rule to handle this kind of logic, but now we can do it with just a few lines of easy-to-read code.

Here to help,

Joel

P.S. If you haven't picked up your copy yet, grab it now! You'll learn a ton and support the work we do here at the same time.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.