NewWe open-sourced 50+ Laravel packages
Custom AI apps, agents and automation — Roundly ConsultingRoundly
All packages
Enums for Laravel

Case lookups

Resolve a case from its name or its readable label, and check whether one exists. The from* variants throw RoundlyConsulting\Enums\Exceptions\EnumException when nothing matches; the tryFrom* variants return null — and short-circuit on a null argument:

NewsCategory::fromName('HotNews');       // NewsCategory::HotNews
NewsCategory::tryFromName('Missing');    // null
NewsCategory::tryFromName(null);         // null

NewsCategory::fromLabel('Hot News');     // NewsCategory::HotNews
NewsCategory::tryFromLabel('Nope');      // null

NewsCategory::hasName('HotNews');        // true
NewsCategory::hasValue('hot-news');      // true
MethodReturnsWhen nothing matches
fromName(string $name)staticThrows EnumException.
tryFromName(?string $name)?staticnull (also for a null argument).
fromLabel(string $label)staticThrows EnumException.
tryFromLabel(?string $label)?staticnull (also for a null argument).
hasName(string $name)boolfalse
hasValue(string|int $value)boolfalse — strict comparison against values() (case names on a pure enum).

Name lookups are exact and case-sensitive (hotnews doesn’t match HotNews). Label lookups compare against readable(), so they match the label in the active locale. hasValue() compares strictly against values() — '5' never matches an int-backed 5 — and on a pure enum it matches the case name.

Looking up by value

Value lookups stay native — PHP’s own from() and tryFrom() on backed enums:

NewsCategory::from('hot-news');     // NewsCategory::HotNews — native PHP
NewsCategory::tryFrom('breaking');  // null — native PHP

Importing data

tryFromLabel() is made for matching human-typed text — a spreadsheet column, a CSV export, an API field — back to a case without try/catch:

use App\Enums\NewsCategory;
use App\Models\Article;

foreach ($rows as $row) {
    $category = NewsCategory::tryFromLabel($row['category'] ?? null);

    if ($category === null) {
        continue; // unknown label: skip or report the row
    }

    Article::create([
        'title' => $row['title'],
        'category' => $category,
    ]);
}

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 crypto

By 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.