Ben Sampson: Using enums in Laravel
Ben Sampson has written up a tutorial showing you how to use enums in Laravel despite them not being natively supported in PHP.
I'm a big fan of enums. Having recently worked for a company who use C#, where enums are used extensively, I've got used to being able to reach for them and miss them when they're not available. I use them for anything with a limited set of possible options, such as days of the week, the status of an order or, as in the examples below, user type.[...] Enums aren't natively supported in PHP but an equivalent is fairly easy to achieve using constants on a class. Futhermore I've created a Laravel package called laravel-enum which allows you access helper functions such as listing keys and values, attaching descriptions to values, and validating requests which are expecting enum values.
He then walks you through the Composer installation of the package and provides an example of it in use. In his example he sets up an enum for types of users, defined in a special UserType
file (admins, members and paid members). He stores these values in the database and then makes use of the type
property on the user to see what type of user they are. He finishes up the post with an example of showing the value of the enum and performing validation on the value with Laravel's built-in validators.