Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dmhall0's avatar

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?

0 likes
4 replies
arwinvdv's avatar

Maybe you can use <p>{{ $user->gender?->label() }}</p>?

dmhall0's avatar

@arwinvdv That is certainly shorter / easier. Still curious if there is a way to control it directly within the enum file? Thanks for the idea.

achatzi's avatar

@dmhall0 One option would be to set your database to have a default value (ex Other). Another would be to add a value in your enum, representing the case the user has not decided yet and then overwrite the setEnumCastableAttribute and getEnumCastableAttributeValue methods in your model to accommodate this.

enum GenderOptions: string
{
    case Undecided = '0';
    case Male = '1';
    case Female = '2';
    case Other = '3';

    public function label()
    {
        return match ($this) {
            self::Male => 'Male',
            self::Female => 'Female',
            self::Other => 'Other',
            self::Undecided => '',
        };
    }
}

//in your model
protected function getEnumCastableAttributeValue($key, $value)
{
    $castType = $this->getCasts()[$key];

    if ($castType == GenderOptions::class && is_null($value)) {
         return GenderOptions::from('0');
    }
    
    return parent::getEnumCastableAttributeValue($key, $value);
}

protected function setEnumCastableAttribute($key, $value)
{
    $enumClass = $this->getCasts()[$key];

    if ($enumClass == GenderOptions::class && !isset($value)) {
          $this->attributes[$key] = '0';
    }
    else {
        parent::setEnumCastableAttribute($key, $value);
    }
}
dmhall0's avatar

@achatzi Wow! That is certainly one way of doing it. I will need to study that one a bit. Thanks!

Please or to participate in this conversation.