In this episode, we dive into validating enums in Laravel, and why it matters for keeping your data clean. We start off by looking at how, without validation, any value can sneak into our database—even ones that aren't part of our enum list. Not ideal!
First up, we look at the old way: using Laravel's in
validation rule, where you manually list all valid statuses as comma-separated values. This works, but of course, it kind of defeats the point of having enums in the first place—you'd have to update the list everywhere if you change your enum.
To make this DRYer, we see how to build this list dynamically from the enum. We grab all the cases from the enum class, extract their values, and implode them into the format the in
rule expects. Now, the validation will always keep up with your enum automatically!
But, Laravel's made things even easier for us. We check out the built-in Enum validation rule. With this, you just point the rule at your enum class, and Laravel takes care of the rest—you don't have to worry about keeping value lists in sync anymore. We check out a couple of ways to use it, both with the direct Enum
rule and via Laravel's Rule
class.
By the end of the video, you'll see how easy and clean it is to validate that incoming values actually match your enum, making your forms and data a lot more robust. Plus, adding new enum values in the future is basically zero-work. Handy!