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!