Using Enums as model casts in Laravel

January 23rd, 2023

Using accessors to return Enums from Laravel model attributes? There's an easier way.

If you're making use of Enums in Laravel for model data (like statuses of an order), you might be reaching for an accessor to return the Enum for that value, like this.

protected function status(): Attribute
{
    return Attribute::make(
        get: fn ($value) => OrderStatus::tryFrom($value)
    );
}

This is perfectly acceptable, but since Laravel 9, you're able to automatically cast this value to an Enum, like this.

protected $casts = [
    'status' => OrderStatus::class
];

That's a much simpler option if you don't have any additional logic you need to perform in an accessor!

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

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

Tagged under