Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dcranmer's avatar

Get enum attribute when querying model (SOLVED)

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?

0 likes
2 replies
LaryAI's avatar
Level 58

To get the project status attribute, you can use an accessor in the Project model. Here's an example:

class Project extends Model
{
    protected $casts = [
        'status_id' => ProjectStatus::class,
    ];

    public function getStatusAttribute()
    {
        return $this->status_id->getName();
    }
}

With this accessor, you can retrieve the project status attribute by calling $project->status.

dcranmer's avatar

Just for the benefit of others, the AI bot's answer is correct as far as it goes, but it doesn't answer the specific question about querying a model. As I suspected, to get the attribute included in a model query, you do need to use an accessor, but you also need to append it in the model. So:

  protected $appends = ['status'];

  public function getStatusAttribute(){
      return $this->status_id->getName();
  }

You will not see the status attribute returned using dd(), but you will see it if you do a query in artisan tinker:

[various other attributes]
    submitter_id: 2731,
    confirmed_at: "2021-08-19 16:09:33",
    leader_id: 2750,
    admin_notes: null,
    edited_fields: null,
    +status: "Published",

Please or to participate in this conversation.