Published: April 18, 2025
1
2
32

⚡You can do some pretty cool stuff with enums in PHP and Laravel. In this thread, I’ve collected some of the useful stuff, such as: - Backed enums - Using enums as factories - Validation - Enum route binding - Model attribute casts 🧵Keep Reading

Image in tweet by Martin Joo

1/7 Backed Enums This is a very basic backed enum with string values:

Image in tweet by Martin Joo

2/7 Enums As Factories You probably already know that. but did you know that you can use it as a factory? You can combine enums with the match operator. For example, if you’re using the strategy pattern:

Image in tweet by Martin Joo

3/7 Enum Validation Since backed enums have a string value, you can easily validate these values in a request:

Image in tweet by Martin Joo

4/7 Route Binding Once again, since backed enums have string values you can use them in route bindings! This is very useful if you have endpoints that filter based on some status:

Image in tweet by Martin Joo

5/7 Model Casts To be able to use enums in where expression (like the example above) you can cast attributes to enums:

Image in tweet by Martin Joo

6/7 Default Attribute Values You can even specify default attribute values with enums. In this example, if you instantiate a new Post, the status will always be ‘draft’ by default:

Image in tweet by Martin Joo

Thank you if you're still here! Just released a new book called Building a database engine. Check out the details here if you want to build your own database: https://thedatabasebook.com/

Share this thread

Read on Twitter

View original thread

Navigate thread

1/8