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.
Prerequisites
To follow this guide, you should have a baseline understanding of
Key Libraries & Tools
- PHP8.1+: The engine providing native enum support.
- LaravelFramework: 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 $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.
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
matchblock,PHPwill 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 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 manualin:draft,publishedstring checks.
