DEV Community

Cover image for Tips using enum in filamentphp
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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs