-
when i want to use enum StatusEnum:string
{
case pending = 'pending',
case accept = 'accepted',
} in migration: ...
$table->string('status');
... in Model: ...
protected $casts = [
'status' => StatusEnum::class
];
... and in Nova Resource: ...
Select::make('Status', 'status')
->options(StatusEnum::cases()),
... , and inserted in db successfully, but can't show in index page and get an error that can't convert App\Enums\StatusEnum to string ! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Off the top of my head, as I write this in the GitHub answer input box, you should be able to do something like enum StatusEnum: string
{
case pending = 'pending';
case accept = 'accepted';
public static function toOptions(): array
{
return collect(self::cases())->mapWithKeys(
fn (StatusEnum $status): array => [$status->name => $status->value]
)->all();
}
}
// ---
Select::make('Status', 'status')
->options(StatusEnum::toOptions()), I haven't tested as I wrote it in the answer input box, but should get you an idea. I also thought a bit of a trait that one could hopefully reuse easily in the enums, that supports both types of enums. trait EnumOptions
{
/**
* @return array<string|int, string|int>
*/
public static function toOptions(): array
{
if (! \is_a(static::class, \UnitEnum::class, allow_string: true)) {
// TODO: Proper message to notify incorrect usage of this trait.
throw new \Exception;
}
$cases = \collect(static::cases());
return \is_a(static::class, \BackedEnum::class, allow_string: true)
? $cases->mapWithKeys(fn (\BackedEnum $case): array => [$case->name => $case->value])->all()
: $cases->mapWithKeys(fn (\UnitEnum $case): array => [$case->name => $case->name])->all();
}
}
// ---
enum StatusEnum: string
{
use EnumOptions;
case pending = 'pending';
case accept = 'accepted';
}
// ---
Select::make('Status', 'status')
->options(StatusEnum::toOptions()), I also recall there being a couple packages on GitHub that enhances enums. It might be possibly one of them has support for something like this, as it's fairly uniform. Let me know how it goes. 🙂 |
Beta Was this translation helpful? Give feedback.
Select::options()
expects an array with two supported structures - 'simple' and groups.For your case, the 'simple' one suffice.
This one expects the array key to be the value that gets saved to the database, and the array value to be what's supposed to be displayed.
UnitEnum::cases()
will hand you a list of the cases, each of which is an instance of the enum.This is why you're getting the Exception, because PHP doesn't support an enum to be
\Stringable
(literally - it's forbidden), and you'll need to convert the key/value to the appropriate values.Off the top of my head, as I write this in the GitHub answer input box, you should be able to do something like