patternphplaravelTip
PHP 8.1 Enums: Backed vs Pure and When to Use Each
Viewed 0 times
PHP 8.1+
enumbacked enumpure enumStatusfromtryFromphp 8.1type safetycast
Error Messages
Problem
PHP projects use string or integer constants to represent finite sets of values (status, role, type). These constants are not type-checked and can hold invalid values. Comparing arbitrary strings is error-prone.
Solution
Use pure enums (enum Status) for named cases with no intrinsic value when you only need identity. Use backed enums (enum Status: string) when you need to serialise to/from a database value or JSON. Implement interfaces on enums to add behaviour. Store as ENUM or VARCHAR in the database and cast with Eloquent's native enum casting.
Why
Enums are a first-class type. A function parameter typed as Status guarantees only valid Status cases are passed. Backed enums provide ::from() and ::tryFrom() for safe deserialisation. PHP 8.1 enums can implement interfaces and have methods.
Gotchas
- Enums cannot be instantiated with new—use Status::Active
- Backed enum ::from() throws ValueError on invalid input—use ::tryFrom() for untrusted input
- Enums cannot have mutable properties; only constants and methods
- Laravel's Eloquent cast: protected $casts = ['status' => Status::class] requires a backed enum
Code Snippets
Backed enum with interface
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string
{
return match($this) {
Status::Draft => 'Draft',
Status::Published => 'Live',
Status::Archived => 'Archived',
};
}
}
// Eloquent model
protected $casts = ['status' => Status::class];
// Usage
if ($post->status === Status::Published) { ... }Revisions (0)
No revisions yet.