bensampo/laravel-enum
Laravel Enum provides a powerful enum implementation for Laravel with class-constant definitions, instantiation, casting, validation, localization, bitwise/flag enums, and an artisan generator. Not recommended for new projects—use native PHP 8.1 enums.
Start by installing the package via Composer (composer require bensampo/laravel-enum) and generating your first enum using php artisan make:enum. Define values as class constants inheriting from BenSampo\Enum\Enum. For legacy projects still on PHP <8.1, use php artisan enum:annotate to generate magic method stubs for IDE autocomplete. For new projects targeting PHP 8.1+, prioritize migrating to native PHP enums—this package is officially discouraged in favor of PHP’s built-in enum support.
Leverage enum instantiation for robust type-hinted method signatures (e.g., function updateStatus(OrderStatus $status)) to prevent invalid states. Use fromValue() and fromKey() for coercion-friendly conversion from database or request input. Combine attribute casting in Eloquent models (protected $casts = ['status' => OrderStatus::class]) for seamless model hydration. For permission systems, use FlaggedEnum with bitwise operators (1 << 0, |, &) to model composite permissions. Integrate validation rules like Rule::in(MyEnum::class) or Rule::enum(MyEnum::class) to enforce valid enum keys/values in requests.
⚠️ Avoid using enums during Laravel’s bootstrap phase (e.g., config/service providers) when still tied to this package—such usages break migration via Rector. ⚠️ Enum::coerce() may silently fail when ambiguous keys/values collide; prefer explicit fromValue()/fromKey() in production. ⚠️ Strict equality (===) between enum instances always returns false (objects are not singletons), but loose comparison (==) works by value—unit tests often miss this. ✅ Use getDescription() and getDescriptionFor($key) for multilingual UI text; override describe() in your enum subclass for dynamic descriptions. ✅ Customize generated stubs via php artisan enum:stubs to enforce team conventions (e.g., docblocks, constants visibility). ✅ When migrating to native PHP enums: replace InvalidEnum*Exception catching with ValueError or use tryFrom() for safe coercion, and handle Enum::getDescription() manually (e.g., via BackedEnum::getBackedCase() + custom locale mapping).
How can I help you explore Laravel packages today?