Laravel Enum is a package by Ben Sampson that adds support for creating enums in PHP and includes a generator for Laravel. Here’s an example of what an Enum class looks like using this package:
1<?php 2 3namespace App\Enums; 4 5use BenSampo\Enum\Enum; 6 7final class UserType extends Enum 8{ 9 const Administrator = 0;10 const Moderator = 1;11 const Subscriber = 2;12 const SuperAdministrator = 3;13}
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:
1<?php23public function store(Request $request)4{5 $this->validate($request, [6 'user_type' => ['required', new EnumValue(UserType::class)],7 ]);8}
You can also validate on the keys using the EnumKey
rule:
1<?php23public function store(Request $request)4{5 $this->validate($request, [6 'user_type' => ['required', new EnumKey(UserType::class)],7 ]);8}
Another Laravel-specific feature that you might find useful is localization:
1<?php 2 3// resources/lang/en/enums.php 4 5use App\Enums\UserType; 6 7return [ 8 9 'user-type' => [10 UserType::Administrator => 'Administrator',11 UserType::SuperAdministrator => 'Super administrator',12 ],1314];1516// resources/lang/es/enums.php17use App\Enums\UserType;1819return [2021 'user-type' => [22 UserType::Administrator => 'Administrador',23 UserType::SuperAdministrator => 'Súper administrador',24 ],2526];
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.
Filed in:
Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.