Laravel Packages

Laravel Enum Package

Published Updated
Laravel Enum Package image

Laravel Enum is a package by Ben Sampson that adds support for creating enums in PHP and includes a generator for Laravel.

Laravel Enum is a simple, extensible, and powerful enumeration implementation for Laravel.

Here’s an example of what an Enum class looks like using this package:

<?php
 
namespace App\Enums;
 
use BenSampo\Enum\Enum;
 
final class UserType extends Enum
{
const Administrator = 0;
const Moderator = 1;
const Subscriber = 2;
const SuperAdministrator = 3;
}

Check out the readme for a list of methods and other examples of how to use this package.

One of my favorite features I noticed from the readme is controller validation using a supplied EnumValue rule:

<?php
 
public function store(Request $request)
{
$this->validate($request, [
'user_type' => ['required', new EnumValue(UserType::class)],
]);
}

You can also validate on the keys using the EnumKey rule:

<?php
 
public function store(Request $request)
{
$this->validate($request, [
'user_type' => ['required', new EnumKey(UserType::class)],
]);
}

Another Laravel-specific feature that you might find useful is localization:

<?php
 
// resources/lang/en/enums.php
 
use App\Enums\UserType;
 
return [
 
'user-type' => [
UserType::Administrator => 'Administrator',
UserType::SuperAdministrator => 'Super administrator',
],
 
];
 
// resources/lang/es/enums.php
use App\Enums\UserType;
 
return [
 
'user-type' => [
UserType::Administrator => 'Administrador',
UserType::SuperAdministrator => 'Súper administrador',
],
 
];

Learn More

Ben Sampson wrote a post Using enums in Laravel which is an excellent follow-up resource to the inspiration and thought process behind his package.

You can view the Laravel Enum source code and get installation instructions from the BenSampo/laravel-enum GitHub repository.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article
Queue totalSize() and JobInterrupted Event in Laravel 13.31 image

Queue totalSize() and JobInterrupted Event in Laravel 13.31

Read article
Find Unexpected Test Inputs with Fuzz for Pest image

Find Unexpected Test Inputs with Fuzz for Pest

Read article