I recently watched Andre Madarang's excellent Laravel bits video on using enums in Laravel for things like status. One thing I'm not clear about is how to get an enum attribute querying the model. I created an enum named "ProjectStatus":
enum ProjectStatus : int
{
case NEW = 1;
case EDITS_PENDING = 2;
case PUBLISHED = 3;
case ON_HOLD = 4;
case ARCHIVED = 5;
public function getName (): string
{
return match ($this) {
self::NEW => 'New',
self::EDITS_PENDING => 'Edits Pending',
self::PUBLISHED => 'Published',
self::ON_HOLD => 'On Hold',
self::ARCHIVED => 'Archived',
default => 'Status Not Found'
};
}
I cast 'status' in the Project model:
protected $casts = [
'status_id' => ProjectStatus::class,
];
My projects table has a status_id column (if this works, I might change this to 'status')
How do I get the project status attribute ; i.e., the status name -- to be retrieved when querying the model, e.g., in ProjectController::show? Do I need to append it? Use an accessor? Both?