#enum to integer in models

1 messages · Page 1 of 1 (latest)

charred berry
#

I have read the docs on casting but I'm still unsure of how to do this, I have an integer column "status" in a table, and in the "process" model I need the integer value of the status to correspond to values like "created" "submitted" "accepted" "completed"

remote aurora
#

You simply make a backed enum class for status and then cast it in the model.

enum Status: int
{
   case CREATED = 1;
   case SUBMITTED = 2;
   ...
}

#Process Model
protected $casts = [
  'status' => \App\Enums\Status::class,
];
charred berry
#

ohhhhh so I need a separate class to define the enum?

remote aurora
#

Yeah.

charred berry
#

that makes sense. and then when I use eloquent to grab a process from the database when I reference $process->status I'll get Created?

#

I'm sorry if this is comon sense

remote aurora
#

You'll get the enum.

charred berry
#

thanks

remote aurora
#

So for example

#
#If the status was 1, this will be true
$process->status === Status::CREATED
#If I wanted the value 1
echo $process->status->value;
#If I wanted the name CREATED
echo $process->status->name;
charred berry
#

dude you're the best

remote aurora
#
#If I want to set the status to submitted
$process->status = Status::SUBMITTED;