DEV Community

Rupadana
Rupadana

Posted on

Tips using enum in filamentphp

Introduction

Enum has been debut on PHP 8.1, for filamentphp user who write Select label or table color in filament resource, Use Enum!.

Problem

How to use enum for support Filamentphp Form & Table?

Solution

Create an Enum in PHP

use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;

enum Status: string implements HasLabel, HasColor
{
    case Pending = 'pending';
    case Success = 'success';
    case Failed = 'failed';

    public function getLabel(): ?string {
        return match($this) {
            self::Pending => 'Pending',
            self::Success => 'Success',
            self::Failed => 'Failed'
        };
    }

    public function getColor(): ?string {
        return match($this) {
            self::Pending => 'warning',
            self::Success => 'success',
            self::Failed => 'danger'
        };
    }
}

Enter fullscreen mode Exit fullscreen mode

Modify laravel model

Cast column status as enum Status

protected $casts = [
    'status' => Status::class
];
Enter fullscreen mode Exit fullscreen mode

Use for filamentphp Table

TextColumn::make('status')
    ->badge()
Enter fullscreen mode Exit fullscreen mode

Use for filamentphp Field

Select::make('status')
    ->options(Status::class)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)