Backed and pure enums
Helpers is designed for backed enums, and every method also works on pure (non-backed) enums: wherever a backed value would be read — values(), storable(), hasValue(), validationRule(), toOptions(), options() and readable() — the case name is used instead.
use RoundlyConsulting\Enums\Helpers;
enum Status
{
use Helpers;
case Active;
case Archived;
}
Status::Active->readable(); // "Active"
Status::labels()->all(); // ['Active', 'Archived']
Status::values()->all(); // ['Active', 'Archived'] — the names stand in for values
Status::toOptions(); // ['Active' => 'Active', 'Archived' => 'Archived']
Status::options()->first()->value; // 'Active'
Status::validationRule(); // 'in:Active,Archived'
Status::hasValue('Active'); // true
Status::fromLabel('Archived'); // Status::Archived
Status::count(); // 2Behaviour by enum type
| Helper | Backed enum | Pure enum |
|---|---|---|
readable(), label(), labels() | Str::headline() of the backed value | Str::headline() of the case name |
toOptions(), toArray() | Keyed by backed value | Keyed by case name |
options() | value = backed value | value = case name |
names(), collect(), count(), random() | Same | Same |
fromName(), tryFromName(), hasName() | Same | Same |
fromLabel(), tryFromLabel() | Match readable() | Match readable() |
is(), isNot(), isIn(), isNotIn(), whenIs*() | Same | Same |
values(), storable() | Backed values | Case names |
validationRule() | in: rule from the backed values | in: rule from the case names |
hasValue() | Strict match on a backed value | Strict match on a case name |
So on a pure enum, values() and storable() return the case names, validationRule() accepts exactly those names, and hasValue() matches a name strictly.
Int-backed enums
use RoundlyConsulting\Enums\Helpers;
enum Priority: int
{
use Helpers;
case Low = 0;
case Medium = 5;
case High = 10;
}
Priority::values(); // [0, 5, 10]
Priority::validationRule(); // 'in:0,5,10'
Priority::hasValue(5); // true
Priority::hasValue('5'); // false — strict comparison
Priority::Medium->readable(); // "5"
Priority::toOptions(); // [0 => '', 5 => '5', 10 => '10']hasValue() compares strictly, so pass an int to an int-backed enum — form input arrives as a string. validationRule() works either way, because Laravel’s in rule compares as strings. Labels are headlined from the value, so numbers stay numbers (5 → “5”) and a 0 value even headlines to an empty string — give int-backed enums real labels by overriding readable(), as shown in Translating labels.
Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.