In this episode, we take a look at how to use Eloquent accessors in Laravel to return an enum instead of just the raw string value from the database. We start off by checking what we currently get when accessing the status
of an order—it's just a string, like "canceled"—and discuss why that's not ideal when we're working with enums in our code.
To fix this, we jump over to the Order model and create an accessor for the status
attribute. Instead of returning the plain string, our accessor now converts it into an OrderStatus
enum using the tryFrom
method. That means any time we access order->status
, we get a proper enum instance back, making it a lot more convenient to work with (like grabbing the label, or using enum methods).
We also talk about some caveats: since we're now returning an enum, comparing it directly with strings elsewhere in the code will break, so you'll want to compare enums to enums from now on.
Overall, this little upgrade makes our code cleaner and more robust when dealing with statuses. Using accessors like this is totally optional, but it's a simple trick that can save you a lot of headaches when working with enums!