Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Enumeration Laravel Package

somnambulist/enumeration

Strongly-typed enumeration value objects for PHP and Laravel. Define constants once and get validation rules, Eloquent casting, instance comparison, and attribute access, plus helpers for safe construction. Ideal for modelling fixed sets such as statuses, types, and roles.

View on GitHub
Deep Wiki
Context7

Getting Started

  • composer require somnambulist/enumeration — this is a plain PHP library. There is no service provider, no config file to publish, and Laravel's package discovery has nothing to do. You just use the classes.
  • First place to look: the src/ directory, specifically the base Enumeration / AbstractEnumeration class. It is a small file — read __callStatic, members(), value(), key(), and the comparison helper before you write your first enum. The test suite is the real documentation; the README is thin.
  • Namespace is Somnambulist\Components\Enumeration\…, not Eloquent\…. If you are migrating off the original eloquent/enumeration, a project-wide namespace find/replace plus a composer remove / composer require is the whole migration.
  • Minimal first use case — kill a set of magic strings in a status column:
use Somnambulist\Components\Enumeration\Enumeration;

final class OrderStatus extends Enumeration
{
    public const PENDING   = 'pending';
    public const PAID      = 'paid';
    public const SHIPPED   = 'shipped';
    public const CANCELLED = 'cancelled';
}

$status = OrderStatus::PENDING();
$status->value();   // 'pending'  — the persisted representation
$status->key();     // 'PENDING'  — the human / log representation
  • Decide up front whether value() or key() is what you write to the database. The library stores both; the choice is a domain decision, not a library one.
  • OrderStatus::members() returns every instance — that is your drop-in source for select options, in: validation rules, and factory states.

Implementation Patterns

  • Single source of truth for status columns. Keep the enum beside the model, add an enum column or a DB check constraint, and stop typing 'pending' anywhere in the app.
  • Eloquent casting. There is no first-party CastsAttributes for recent Laravel in the base library — write a ten-line cast: OrderStatus::from($value) on get, $value->value() on set (check src/ for a shipped cast first). Laravel 9+ native backed enums work too, but you lose the enumeration helpers.
  • Validation. Build the rule from members instead of hard-coding strings:
Rule::in(array_map(fn ($m) => $m->value(), OrderStatus::members()))

Better: a small custom rule that takes the class string — new EnumRule(OrderStatus::class) — so it is reusable across requests.

  • Factory states. Order::factory()->state(['status' => OrderStatus::PENDING()]). Referencing the enum in factories is what keeps seed data honest.
  • Comparisons in business logic. Use the library's equality helper rather than ===, since it survives serialization round-trips:
if ($order->status->equals(OrderStatus::PAID())) { /* ... */ }
  • API resources. Never return the enum object raw. Choose per endpoint: ->value() for machine clients, ->key() for labels, or ['key' => ..., 'value' => ...] for a dropdown payload.
  • Blade selects. A tiny collection helper that maps members() to value/label pairs keeps views readable:
@foreach (OrderStatus::members() as $status)
    <option value="{{ $status->value() }}">{{ $status->key() }}</option>
@endforeach
  • State machines. Treat the enum as the vocabulary and put transition rules in one dedicated class keyed by enum instance — not in switch statements scattered across controllers.
  • Testing. Loop members() to assert every status is handled by policies, factories, and admin filters. That exhaustive-coverage test is where enums pay for themselves.

Gotchas and Tips

  • The namespace is the migration. Class names mirror eloquent/enumeration, but the namespace is Somnambulist\Components\Enumeration. Every blog post and Stack Overflow answer you find will use the old one — translate mentally.
  • Constants vs instances. You compare against OrderStatus::PENDING() (a singleton instance), not OrderStatus::PENDING (a string constant). Forgetting the parentheses is the number-one bug with this library, and PHP will not warn you.
  • Hydration cost. Members are resolved and cached per class, so accessors are cheap — but don't call members() inside a loop over thousands of rows. Hoist it.
  • Distinct values. Constants must have unique values or from()-style lookups silently pick one. If you need aliases, add a separate method; do not duplicate values.
  • Serialization. json_encode on the enum object depends on JsonSerializable support and will leak internal properties if you are not careful. Always convert explicitly at the API boundary.
  • Unknown DB values. from() throws on an unrecognised value. In your cast, decide deliberately whether legacy rows should throw (fail fast) or return null (tolerant read) — and document it.
  • Debugging. var_dump shows the internal value and key. Log ->key() so you can grep for the human name rather than the storage value.
  • Low adoption, single maintainer. Zero stars and one active author mean you should pin the minor version, read the changelog on every bump, and keep enum classes thin (constants plus label helpers only). That makes swapping to native PHP enums or spatie/enum later a mechanical change.
  • Extension points. Subclass a shared App\Enum base to override __toString and add consistent label() / description() / badgeColor() helpers. The library deliberately leaves presentation policy to you — centralise it once.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings