Coding

Working with Enums in Laravel

Posted on Fri, Feb 28, 2025

Working with Enums in Laravel

Working with Enums in Laravel is pretty simple once you know how. In this quick post, I'll show you how I use Enums to store values for an alert popup.

Enums

First, we need to create a file called App/Enums/StatusTypesEnum.php and add the following code (the colors can be adjusted to suit your needs):

<?php  

namespace App\Enums;  

enum StatusTypesEnum: string  
{  
    case SUCCESS = 'success';  
    case INFO = 'info';  
    case DANGER = 'danger';  

    public function colours(): string  
    {  
        return match ($this) {  
            StatusTypesEnum::SUCCESS => 'bg-green-600',  
            StatusTypesEnum::INFO => 'bg-sky-600',  
            StatusTypesEnum::DANGER => 'bg-rose-500',  
        };  
    }  
}  

Livewire Component

For this example, I am using Livewire to display the alert on the page.

First, we create a Livewire component and view:

php artisan make:livewire StatusBar  

Now, we add the necessary code:

<?php  

namespace App\Livewire;  

use App\Enums\StatusTypesEnum;  
use Illuminate\Contracts\View\View;  
use Livewire\Component;  

class StatusBar extends Component  
{  
    public $show = false;  

    public function render(): View  
    {  
        $status = Status::first();  

        return view('livewire.status-bar')->with([  
            'message' => $status->message,  
            'alert_type_colour' => StatusTypesEnum::from($status->type)->colours(),  
        ]);  
    }  
}  

And now for the view:

<div>  
    <div class="flex items-center justify-center gap-x-6 {{ $alert_type_colour }} px-6 py-2.5 sm:px-3.5">  
        <p class="text-sm/6 text-white">  
            <a href="#">  
                {{ $message }}  
            </a>  
        </p>  
    </div>  
</div>  

Explanation

What I have done here is define the cases for each status in the StatusTypesEnum Enum. I then define a function for the colors associated with each status.

In the StatusBar Livewire component, I use the ::from() method to find an Enum case from the value stored in the database (which, in my case, is 'success'). From this value, we use the ->colours() function to get the corresponding color class.