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.
9 episodes 31 mins

Overview

Enums make working with multiple potential column values a breeze (think order statuses). Let's use an Enum in Laravel and cover storing, validating and accessing Enums.

By the end of the course, you'll be able to implement Enums in Laravel with ease, and make sure your multiple choice column data is strict and easy to globally update across your entire application.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Comments

No comments, yet. Be the first to leave a comment.