Home > Net >  Laravel 9: how to use enums in blade (<select>)?
Laravel 9: how to use enums in blade (<select>)?

Time:10-05

I read this awesome article before asking here.

I created an enum class CaseSeverity to use across all forms that needs it. I couldn't find a way to use the enum within the blade, specifically listing the cases within <select> options.

I did a workaround by mkaing a static function in the enum class:

public static function option()
    {
        return [
            'high' => 'high',
            'medium' => 'medium',
            'low' => 'low'
        ];
    }

Then made a helper function to fetch the array:

 if(!function_exists('case_severity')) {
    // Get case severity enum
    function case_severity() {
        return CaseSeverity::option();
    }
 }

Then used that in the blade:

<select 
    name="severity" required
    data-control="select2"
    data-placeholder="Select"
    data-hide-search="true">
      <option></option>
      @foreach (case_severity() as $item)
        <option value="{{ $item }}"> {{ $item }} </option>
      @endforeach
 </select>

Yes, it working as I want it to be, but I have a strong feeling that there is a better way of doing it? Because to me the code/enum cases are repeated.

Entire enum class:

enum CaseSeverity : string
{
    case High = 'high';
    case Medium = 'medium';
    case Low = 'low';

    // Coloring the cases to use in datatables as badges
    public function color(): string
    {
        return match($this)
        {
            self::High => 'badge-danger',
            self::Medium => 'badge-warning',
            self::Low => 'badge-success',
        };
    }

    // To use in <select> fields
    public static function option()
    {
        return [
            'high' => 'high',
            'medium' => 'medium',
            'low' => 'low'
        ];
    }
}

CodePudding user response:

You could do it like this if you like it bettter.

In your App\Enums\Severity file:

    public static function values(): array
    {
        return array_column(self::cases(), 'name', 'value');
    }

Then you can loop through the values:

    @foreach(App\Enums\Severity::values() as $key=>$value)
        <option value="{{ $key }}">{{ $value }}</option>
    @endforeach
  • Related