Skip to content
OpenCloseEsc
Tips
  • Laravel
  • enums
  • php

Give every enum the same ten lines

A small trait adds values(), names() and options() to every backed enum, so whereIn clauses, validation lists and select inputs read the cases instead of a copied array.

1 min read

Every project ends up with the same helpers on every enum. Write them once as a trait in app/Concerns and use it in each enum.

trait EnumHelpers
{
    /** @return array<int, string|int> */
    public static function values(): array
    {
        return array_column(self::cases(), 'value');
    }
 
    /** @return array<int, string> */
    public static function names(): array
    {
        return array_column(self::cases(), 'name');
    }
 
    /** @return array<int, array{value: string|int, label: string}> */
    public static function options(): array
    {
        return array_map(
            fn (self $case) => ['value' => $case->value, 'label' => $case->label()],
            self::cases(),
        );
    }
}

Then User::whereIn('status', UserStatus::values()), Rule::in(UserStatus::values()) for a legacy rule, and UserStatus::options() for a select. A new case shows up everywhere without a second edit.