Enum in Laravel and Filament

Enum in Laravel and Filament

ยท

2 min read

I am currently using Enum a lot in my projects for status. And it was really good, and when I added this to Laravel and Livewire, it just got better.

You can learn about Enum here. Now let's start learning about how enums can simplify decisions.

I am using status, which can change in the future, and managing using the "Tiny Integer" database field. I avoid the MySQL database enum field. Let's use Enum with our project now.

Laravel does not have command lines for enums yet. So we have to do this manually. Just create a directory inside 'app' and name it 'Enum," so here is the full path of the directory.

app\Enums

Now we will be using post status for draft and publish status. Let's write the code.

//File "app\Enums\PostStatus.php

<?php

namespace App\Enums;

enum PostStatus: int
{
    case DRAFT = 0;
    case PUBLISHED = 1;

    public const DEFAULT = self::DRAFT->value;

    public function getLabel(): ?string
    {
        return $this->name;
    }
}

Now that's all you need. We also need to define cast inside the model.

protected $casts = [
    'status'=> App\Enums\PostStatus::class
];

This works fine with Laravel; now I need them to work with Filament too. I have also extended useIcon and useColor, so when I use status inside the filament, it will get them using this. Let's see the full code here.

// app/Enums/PostStatus.php
<?php

namespace App\Enums;

use Filament\Support\Colors\Color;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasIcon;
use Filament\Support\Contracts\HasLabel;

enum PostStatus: int implements HasColor, HasIcon, HasLabel
{
    case DRAFT = 0; //When Created with only html
    case PROCESSED = 1; //When converted from html to markdown
    case ERROR = 2; //Any error code
    case PUBLISHED = 3; //Successfully published

    public const DEFAULT = self::DRAFT->value;

    public function getLabel(): ?string
    {
        return $this->name;
    }

    public function getIcon(): ?string
    {
        return match ($this) {
            self::DRAFT => 'heroicon-o-pencil-square',
            self::PROCESSED => 'heroicon-o-forward',
            self::ERROR => 'heroicon-o-exclamation-triangle',
            self::PUBLISHED => 'heroicon-o-shield-check',
        };
    }

    public function getColor(): string | array | null
    {
        return match ($this) {
            self::DRAFT => Color::Green,
            self::PROCESSED => Color::Blue,
            self::ERROR => Color::Red,
            self::PUBLISHED => Color::Orange,
        };
    }
}

Now I can use colours and icons, and filament will get the information from its enum. Pretty good tricks.

IconColumn::make('status')

This code in the filament table will get the icons for status and display them inside the table. No icon needs to pass. If you need to change the icon for any reason, you just need to change one icon.

ย