Supercharge Your Laravel App with Enums

Overview

Modern web development often involves managing sets of fixed values, such as order statuses or user roles. While strings or constants get the job done, they often lead to "magic strings" scattered throughout a codebase.

provide a type-safe way to define these collections, and
Laravel
offers deep integration that makes them feel like a first-class citizen. This tutorial explores how to move beyond basic enum definitions to using them for model casting, route binding, and validation.

Prerequisites

To follow this guide, you should have a baseline understanding of

8.1+ (where enums were introduced) and the
Laravel
framework. Familiarity with
Eloquent
models and basic routing will help you grasp the integration points more quickly.

Key Libraries & Tools

  • PHP
    8.1+
    : The engine providing native enum support.
  • Laravel
    Framework
    : Provides the glue for casting, validation, and route binding.
  • Eloquent
    : The ORM used to cast database values into enum objects.
  • Artisan
    : The command-line tool used to generate enum files.

Code Walkthrough

Creating Backed Enums

Instead of creating pure enums, we use backed enums to ensure there is a scalar value (string or integer) for database storage. Use the Artisan command to scaffold the file:

php artisan make:enum PostStatus

Inside the file, define your cases and add helper methods like label() or color() to keep presentation logic out of your views:

enum PostStatus: string {
    case Draft = "draft";
    case Published = "published";

    public function label(): string {
        return match($this) {
            self::Draft => "Draft",
            self::Published => "Published",
        };
    }
}

Eloquent Casting

To tell

that a database string should be treated as an enum, use the $casts property in your model. This automatically transforms the attribute into an object when accessed.

protected $casts = [
    "status" => PostStatus::class,
    "tags" => "as_enum_collection:" . PostTag::class,
];

Route Model Binding

You can type-hint enums directly in your controller methods.

will automatically attempt to resolve the URL parameter into the corresponding enum case, returning a 404 if no match is found.

public function show(PostTag $tag) {
    return Post::whereJsonContains("tags", $tag->value)->get();
}

Syntax Notes

  • Match Expressions: These are perfect for enums. They ensure exhaustive checks; if you add a new case to the enum but forget to update the match block,
    PHP
    will throw an error.
  • Cases Method: PostStatus::cases() returns an array of all cases, which is ideal for populating <select> dropdowns in Blade templates.

Practical Examples

Beyond status labels, enums excel in Queue Management. Instead of hardcoding queue names like "high" or "low" in your dispatch logic, use a QueuePriority enum. This prevents typos and centralizes queue naming conventions. Enums also streamline API Development, as

's json_encode natively handles enums by returning their backed value.

Tips & Gotchas

  • Database Constraints: Even if you use enums in
    PHP
    , keep your database column as a string. Native database enum types are notoriously difficult to migrate or modify later.
  • Validation: Always use the Rule::enum() class in your request validation. It ensures the incoming request data matches a valid case defined in your enum file, eliminating the need for manual in:draft,published string checks.
3 min read