murtaza1904's avatar

How can I use enum class in migration

I have a program day column in the table which has enum type. Right now I define the allows value of enum column like this

$table->enum('program_day',['monday','tuesday','wednesday','thursday','friday','saturday','sunday']);

I do have an enum class which already contain these cases. Enum class

enum DayEnum: string
{
    case MONDAY = 'monday';
    case TUESDAY = 'tuesday';
    case WEDNESDAY = 'wednesday';
    case THURSDAY = 'thursday';
    case FRIDAY = 'friday';
    case SATURDAY = 'saturday';
    case SUNDAY = 'sunday';

}

How can I use this class to be define in migration class something like this

$table->enum('program_day', \App\Enums\DayEnum::cases());
0 likes
5 replies
murtaza1904's avatar
murtaza1904
OP
Best Answer
Level 2

@martinbean The method returns array of an object of enum class and I found the solution for it.

array_column(DayEnum::cases(), 'value')

I achieve the functionality using above code but if there is a better way of doing that?

jbloomstrom's avatar

I have something similar in my project. You could add a static method to the enum if you think it's cleaner:

enum DayEnum: string
{
  case MONDAY = 'monday';
  case TUESDAY = 'tuesday';
  case WEDNESDAY = 'wednesday';
  case THURSDAY = 'thursday';
  case FRIDAY = 'friday';
  case SATURDAY = 'saturday';
  case SUNDAY = 'sunday';

  public static function toArray(): array
  {
      return array_column(DayEnum::cases(), 'value');
  }    
}
$table->enum('program_day', \App\Enums\DayEnum::toArray());
8 likes
derdek's avatar

@jbloomstrom It's a good solution, but I made a few changes.:

enum DayEnum: string
{
  case MONDAY = 'monday';
  case TUESDAY = 'tuesday';
  case WEDNESDAY = 'wednesday';
  case THURSDAY = 'thursday';
  case FRIDAY = 'friday';
  case SATURDAY = 'saturday';
  case SUNDAY = 'sunday';

  public static function toArray(): array
  {
      return array_column(self::cases(), 'value');
  }    
}
3 likes

Please or to participate in this conversation.