Replies: 3 comments 3 replies
-
There are a few packages for this. Look at Enumhancer for example. |
Beta Was this translation helpful? Give feedback.
3 replies
-
So I think if there was an enum SomeEnum: string implements Optionable
{
public function asOption(): Option
{
return [$this->value => $this->label()];
// Or maybe using a class for strictness/clarity
return new Option(
key: $this->value,
value: $this->label()
);
}
}
// Then...
collect(SomeEnum::cases)->options(); |
Beta Was this translation helpful? Give feedback.
0 replies
-
public static function asArray(): array
{
$names = array_column(BackedEnum::cases(), 'name');
$values = array_column(BackedEnum::cases(), 'value');
if (count($values) > 0) {
return array_combine($names, $values);
}
return $names;
}
public static function asCollection(): \Illuminate\Support\Collection
{
return collect(self::asArray());
} Extract this in a trait and you are good to go. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I often find myself doing something like this to give me a well-formatted array of
BackedEnum
key-values (principally it could work withUnitEnum
too) and I'm not sure if there's a better way:But it's getting kind of annoying to put that everywhere. So I move it to the enum:
This is fine when I want all/some subset of the available enum options and I'm calling the enum directly, but it doesn't help when I'm dealing with an
AsEnumCollection
cast from that enum.In those cases, I end up with a
Collection
and now I still have to write:So, I could let the
SomeEnum:options()
method accept a collection:Which keeps all of this logic together, but then I still gotta do:
Which feels kinda weird - I have a collection of the enum, which I pass into the enum, to run some code on.
I really just want a
Collection
method that does some of this for me:I am tempted to put something together for this, but wanted to make sure I'm not missing something before I start on it.
Does anyone else have this problem? How do you solve it?
Beta Was this translation helpful? Give feedback.
All reactions