Quick start
Add the RoundlyConsulting\Enums\Helpers trait to any enum. Backed (string or int) enums get every method:
namespace App\Enums;
use RoundlyConsulting\Enums\Helpers;
enum NewsCategory: string
{
use Helpers;
case HotNews = 'hot-news';
case RegularNews = 'regular-news';
case PrivateNews = 'private-news';
}Every helper is now available on the enum and its cases:
NewsCategory::HotNews->label(); // "Hot News"
NewsCategory::values(); // ['hot-news', 'regular-news', 'private-news']
NewsCategory::toOptions(); // ['hot-news' => 'Hot News', 'regular-news' => 'Regular News', ...]
NewsCategory::options(); // Collection<EnumOption> for JS selects
NewsCategory::fromName('HotNews'); // NewsCategory::HotNews
NewsCategory::tryFromLabel('Nope'); // null
NewsCategory::validationRule(); // 'in:hot-news,regular-news,private-news'
NewsCategory::random(); // a random case
NewsCategory::count(); // 3
NewsCategory::HotNews->isIn([NewsCategory::HotNews, NewsCategory::RegularNews]); // trueThe collection helpers — names(), values(), labels(), toOptions() and friends — return Illuminate\Support\Collection instances; the comments show their contents as arrays for readability.
With Eloquent
The trait sits happily next to Laravel’s native enum cast, so a model attribute comes back as a case with every helper on it:
use App\Enums\NewsCategory;
use Illuminate\Database\Eloquent\Model;
final class Article extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'category' => NewsCategory::class,
];
}
}
$article->category->label(); // "Hot News"
$article->category->is(NewsCategory::PrivateNews); // falseShow 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.