Laravel Php 8.1 how to convert enum cases to array for select input

Viewed 320

I got this enum class of periods or terms:

Term.php

<?php

namespace App\Enums;

enum Term : string
{
    case ONE_MONTH = '1 month';
    case THREE_MONTHS = '3 months';
    case SIX_MONTHS = '6 months';
    case TWELVE_MONTHS = '12 months';
}

So I have tested the following with dump

dd(array_map(
   fn (Term $term) => $term->value,
   Term::cases()
));

it outputs:

^ array:4 [▼
  0 => "1 month"
  1 => "3 months"
  2 => "6 months"
  3 => "12 months"
]

Now I want to pass each value into a Select input (of filamentphp.com ) like so:

Forms\Components\Select::make('term')->options([
       array_map(
          fn (Term $term) => $term->value,
          Term::cases()
       )
   //Term::ONE_MONTH->value=>TERM::ONE_MONTH->name
]),

But I get the following error:

Filament\Forms\Components\Select::isOptionDisabled(): Argument #2 ($label) must be of type string, array given,

Well, it looks like I need to get the following syntax (as shown in the documentation):

use Filament\Forms\Components\Select;
 
Select::make('status')
    ->options([
        'draft' => 'Draft',
        'review' => 'In review',
        'published' => 'Published',
    ])

So what am I missing to get the enum class values displayed in an input form?

2 Answers

Just tried your code locally and based on your code I see that you are passing an array to filament select option. As the error says you should pass a string into label. But you are passing an array to it. Check below dump it will pass 0 as the value and array ( "ONE_MONTH" => "1 month") as the label.

^ array:4 [▼
  0 => array:1 [▼
    "ONE_MONTH" => "1 month"
  ]
  1 => array:1 [▼
    "THREE_MONTHS" => "3 months"
  ]
  2 => array:1 [▼
    "SIX_MONTHS" => "6 months"
  ]
  3 => array:1 [▼
    "TWELVE_MONTHS" => "12 months"
  ]
]

Just mapping enums as key-value paire will fix the issue

 $terms = [];

 foreach (Term::cases() as $value) {
   $terms[$value->name] = $value->value;
 }

Above code will return an array like below

^ array:4 [▼
  "ONE_MONTH" => "1 month"
  "THREE_MONTHS" => "3 months"
  "SIX_MONTHS" => "6 months"
  "TWELVE_MONTHS" => "12 months"
]

I have tested with one of my local project and see below working screenshots and code

public static function form(Form $form): Form
    {

        $values = [];

        foreach (Term::cases() as $value) {
            $values[$value->name] = $value->value;
        }
        return $form
            ->schema([
                Select::make('terms')
                    ->options($values),

enter image description here

Thanks

Related