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

Enum Getter Laravel Package

cable8mm/enum-getter

A lightweight Laravel/PHP package that provides convenient getter helpers for enums, making it easy to retrieve cases, values, labels, and key-value arrays for forms, validation rules, and select inputs. Keeps enum usage clean, consistent, and reusable across Laravel applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require cable8mm/enum-getter

There is no service provider or config file to publish for typical use — the package is a trait-based helper for PHP 8.1+ enums. Your first stop should be the README's Quick Start section (expanded substantially in v2.2.0), which now clearly separates the two concepts you will use constantly:

  • key — the enum case name (e.g. Pending, Active), used for storage, routing, and comparisons.
  • label — the human-readable string (e.g. "Pending", "Active"), used in UI.

Minimal first use case — a status enum feeding a <select>:

use Cable8mm\EnumGetter\EnumGetable;

enum OrderStatus: string
{
    use EnumGetable;

    case Pending  = 'pending';
    case Shipped  = 'shipped';
    case Cancelled = 'cancelled';

    public function label(): string
    {
        return match ($this) {
            self::Pending   => 'Awaiting shipment',
            self::Shipped   => 'On the way',
            self::Cancelled => 'Cancelled',
        };
    }
}

Then in a controller:

return view('orders.edit', [
    'statuses' => OrderStatus::toArray(), // key => label pairs
]);

If you only read one thing before your first PR, read the "PHP built-in enum methods" section added in v2.2.0 — it tells you which helpers you actually need versus which are already provided by cases(), from(), and tryFrom().

Implementation Patterns

Select inputs and API payloads. Use the key/label array helper to populate dropdowns and to build JSON responses for frontends. Because keys come from case names, they remain stable even if you change the underlying backing value — useful when you migrate a database column.

Inbound request resolution with fromKey() (new in v2.2.0). This is the headline feature. When a form or API submits the enum key rather than the backed value, resolve it directly:

$status = OrderStatus::fromKey($request->validated('status'));

This complements from()/tryFrom(), which operate on the backing value. The distinction matters in codebases where the key is the wire format (e.g. JavaScript sends "Pending") and the backing value is the persistence format ("pending").

Validation. Pair the package with Laravel's Rule::enum() when clients send backing values, or with an in: rule built from the keys when they send keys:

'status' => ['required', Rule::in(OrderStatus::getKeys())],

Eloquent casts and route binding. Cast the attribute to the enum normally ('status' => OrderStatus::class). For route model binding or implicit resolution from a URL segment, use tryFrom() when the segment is a backed value and fromKey() when it is a case name — the latter will throw, which is what you want for a 404 path, but see the gotchas below.

Blade and API resources. Keep label logic in the enum (a label() method) rather than in views. Then $order->status->label() reads cleanly in Blade, and OrderStatus::toArray() serves as the single source of truth for both the select and any admin filter UI.

Localisation. If labels need translating, return __('enums.order_status.'.$this->name) from label(). The package helpers stay unchanged; only your label method grows.

Gotchas and Tips

fromKey() throws — wrap it deliberately. The release notes call out "error handling," meaning an unknown key raises a ValueError. In a controller that is correct behaviour (let it become a 500 or catch it and return a 422), but in batch jobs or CSV importers use a guard:

$status = rescue(fn () => OrderStatus::fromKey($row['status']), OrderStatus::Pending);

Keys vs labels is the number-one source of bugs. The v2.2.0 README rewrite exists because people conflate them. Keys are case names and are case-sensitive ("pending" is not the key "Pending"). Labels are whatever your label() returns and can change freely without breaking stored data — never persist a label.

Distinguish the three "identifier" concepts. A case has a name (key), a backed value, and a label. from() reads the value, fromKey() reads the name. Mixing them up produces silent null returns from tryFrom() and confusing ValueErrors from fromKey().

Don't duplicate what PHP already gives you. As the new docs section points out, cases(), from(), tryFrom(), and name/value are built in. Use the package for the array-shaping and label plumbing, not as a wrapper around primitives.

Unit tests are cheap here. Enums are pure, so table-driven tests asserting fromKey() round-trips every case, and that toArray() keys match getKeys(), catch regressions in seconds:

foreach (OrderStatus::cases() as $case) {
    expect(OrderStatus::fromKey($case->name))->toBe($case);
}

Watch the PHP floor. Enum support requires PHP 8.1; the trait-based approach also assumes your enums declare a backing type if you use value helpers. If you run mixed pure and backed enums, verify which helpers each supports before relying on them.

Extension points are your own enums. There is nothing to configure globally — the trait is the extension point. If you need shared behaviour across enums (e.g. a consistent label() fallback using Str::headline($this->name)), define your own HasLabels trait and compose it with EnumGetable.

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.
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle
adachsoft/api-version-bundle
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
cgv/localized-resource