This episode is for members only

Sign up to access "Enums in Laravel" right now.

Get started
Already a member? Sign in to continue
Playing
09. Enum model casts

Transcript

00:00
Earlier on, we created a status accessor. So when we access the status of each of our models,
00:08
this goes ahead and gives us back an order status. And we plug that from the value in the database and then give back the num that we want to use. Now, there's actually a much easier way
00:19
to do this via Laravel Casts. So what we're going to do is just get rid of this status accessor. If we head over to the browser, you'll
00:28
see that I'll break it because we're trying to access label on a string, which, of course, is not going to work. And let's go ahead and implement the much easier solution.
00:37
Now, it doesn't matter which solution you use here. You may need an accessor if you have additional logic to perform here. But if you don't, which is our case at the moment,
00:46
then you can very easily create out a casts property within your model. You can choose the column that you want to cast from. And you can actually define the enum out in here.
00:58
So our enum is order status. And we just need the fully qualified class name to that. And Laravel will handle this for you. So it will automatically cast the status to an enum
01:10
based on the value that it's given. Let's come over and give that a refresh. And you can see we get exactly what we had before, but, of course, in just a few lines of code
01:19
compared to this accessor. So whichever solution you choose, it really doesn't matter. But, of course, this is a lot simpler.

Episode summary

In this episode, we take a closer look at how to simplify our code by using Laravel's enum casts with models. Previously, we had set up a custom accessor to convert the status attribute from the database into an enum, which worked but involved a bit of extra code.

Now, we're going to ditch that accessor and embrace Laravel's built-in casting features. You'll see that by declaring a casts property on your model and specifying your enum, Laravel takes care of the heavy lifting for you. When you access the status attribute, it will automatically be cast to the enum class, making your code cleaner and easier to maintain.

We walk through breaking the previous accessor-based approach to demonstrate why it's problematic, and then quickly fix it with the casts array, showing the huge reduction in boilerplate. Plus, you'll learn when it still makes sense to use an accessor, like if you need complex logic. Overall, this episode is all about keeping things simple and letting Laravel do the work!

Episode discussion

No comments, yet. Be the first!