Installation
composer require henzeb/enumhancer
No service provider or facade needed—just autoload and use.
First Use Case: Basic Enum Definition
Define a simple enum in a file (e.g., app/Enums/UserRole.php):
use HenzeB\Enumhancer\Enum;
enum UserRole: string
{
use Enum;
case ADMIN = 'admin';
case EDITOR = 'editor';
case VIEWER = 'viewer';
}
Key Features to Try Immediately
UserRole::from('AdMiN'); // Returns UserRole::ADMIN
UserRole::ADMIN->value; // 'admin' (string)
UserRole::ADMIN->toString(); // 'ADMIN'
UserRole::all()->pluck('value'); // ['admin', 'editor', 'viewer']
Where to Look First
Use fromDatabase() for case-insensitive DB value handling:
$role = UserRole::fromDatabase('ADMIN'); // Works for 'admin', 'Admin', etc.
Model Casting:
use HenzeB\Enumhancer\Casts\EnumCast;
protected $casts = [
'role' => EnumCast::class,
];
Leverage isValid() for input validation:
if (UserRole::isValid('editor')) {
// Proceed
}
Form Request Example:
public function rules()
{
return [
'role' => ['required', Rule::in(UserRole::all()->pluck('value'))],
];
}
Use toArray() or jsonSerialize() for consistent serialization:
return response()->json([
'role' => UserRole::ADMIN->toArray(), // ['value' => 'admin', 'name' => 'ADMIN']
]);
Extend Enum for reusable traits:
trait HasDescription {
public function description(): string {
return match($this) {
self::ADMIN => 'Full access',
self::EDITOR => 'Limited access',
default => 'Read-only',
};
}
}
Apply to enum:
enum UserRole: string {
use Enum, HasDescription;
// ...
}
Use getLabel() with a custom resolver:
UserRole::setLabelResolver(function (string $value) {
return __("roles.{$value}");
});
protected $casts = [
'permission' => EnumCast::class,
];
public function scopeWithRole(Builder $query, UserRole $role)
{
return $query->where('role', $role->value);
}
assertIs() with Enumhancer's assertions:
$this->assertIs(UserRole::class, UserRole::from('admin'));
from() for tests:
UserRole::shouldReceive('from')->andReturn(UserRole::VIEWER);
all() result:
$roles = Cache::remember('user_roles', now()->addHour(), function () {
return UserRole::all();
});
Case Sensitivity in Backed Enums
Enumhancer is case-agnostic, backed enums (e.g., enum UserRole: string) will still enforce strict type matching for raw values.from() or fromDatabase() instead of direct casting:
// ❌ Avoid:
UserRole::from('ADMIN')->value; // May fail if DB returns 'admin'
// ✅ Use:
UserRole::fromDatabase('admin'); // Works
Overriding Default Methods
Enum with custom traits/methods, ensure they don’t conflict with Enumhancer's magic methods (e.g., __toString()).custom() or use namespaces:
public function customDescription(): string { ... }
Serialization Quirks
jsonSerialize() may not work as expected if the enum implements custom serialization logic.toArray() or toJson():
json_encode(UserRole::ADMIN->toArray());
AGPL License Implications
Enumhancer or applications using it if they interact with users over a network.Unknown Enum Values
from() returns null, check for typos or whitespace:
UserRole::from(' admin ')->trimmed(); // Helper to trim values
Method Not Found
use Enum; trait is at the top of the enum class (before case definitions).Performance Bottlenecks
all() in loops. Cache results or use lazy evaluation:
UserRole::all()->filter(fn ($role) => $role->value === 'admin');
Custom Label Resolvers Override default label behavior globally:
UserRole::setLabelResolver(function (UserRole $enum) {
return "Role: {$enum->name} ({$enum->value})";
});
Adding Validation Rules Extend the enum with custom validation logic:
enum UserRole: string {
use Enum;
public function isActive(): bool {
return $this !== self::VIEWER;
}
}
Database-Specific Adapters Create a custom adapter for non-standard DB value formats:
UserRole::setDatabaseAdapter(function (string $value) {
return strtoupper($value); // Force uppercase for DB
});
Event Dispatching
Trigger events on enum operations (e.g., onFrom()):
UserRole::onFrom(function (string $value, UserRole $enum) {
event(new EnumUsed($enum, $value));
});
Default Label Format
ADMIN → "ADMIN").UserRole::setLabelFormat('{name} ({value})');
Strict Mode
from() calls:
UserRole::setStrict(true);
UserRole::from('invalid'); // Throws \InvalidArgumentException
Backed Enum Handling
value property matches the enum’s type (e.g., string, int). Mismatches may cause silent failures.How can I help you explore Laravel packages today?