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.