Getting to know Enums

This is a neat implementation of enums where I don't need to put most of my enums in the model.

//create folder and file called Enums/Relationship

<?php

namespace App\Enums;

enum Relationship : int
{
    case FATHER = 1;
    case MOTHER = 2;
    case OTHER = 3;

    public function getName() : string
    {
        return match($this) {
            self::FATHER => 'Father',
            self::MOTHER => 'Mother',
            self::OTHER => 'Other',
            default => 'Not found',
        };
    }

    public function getStyle() : string {
        return match($this) {
            self::FATHER => 'bg-yellow-200 text-yellow-800',
            self::MOTHER => 'bg-purple-200 text-purple-800',
            self::OTHER => 'bg-green-200 text-green-800',
            default => '',
        };
    }
}

To list all the relationship

@foreach (\App\Enums\Relationship::cases() as $relationship)
	{{ $status->getName() }}
@endforeach

to show the enum from Integer

App\Enums\Relationship::tryFrom($student->guardian)->getName();
App\Enums\Relationship::tryFrom($student->guardian)->getStyles();

to validate

$request->validate([
	'relationship' => [new Enum(Status::class)]
]);

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe