Maybe you can use <p>{{ $user->gender?->label() }}</p>?
Sep 12, 2023
4
Level 1
ENUM null Optional?
I have enum for gender as follows:
enum GenderOptions: string
{
case Male = '1';
case Female = '2';
case Other = '3';
public function label()
{
return match ($this) {
self::Male => 'Male',
self::Female => 'Female',
self::Other => 'Other',
};
}
}
Until a user selects their gender in a dropdown field this is null in the database. When I display all users in a table with a column for their gender I get the following error:
Call to a member function label() on null
My code for displaying gender is:
<p>{{ $user->gender->label() }}</p>
My workaround is:
<p>{{ optional($user->gender)->label() }}</p>
I am not a fan of this as I have other enums and to require this optional code everywhere seems to be a pain.
Is there something I can put in the actual enum file to help it deal with this?
Please or to participate in this conversation.