Using this library is no longer recommended, especially for new projects. PHP 8.1 supports enums natively.
See #332.
Simple, extensible and powerful enumeration implementation for Laravel.
Enum key value pairs as class constants
Full-featured suite of methods
Enum instantiation
Flagged/Bitwise enums
Type hinting
Attribute casting
Enum artisan generator
Validation rules for passing enum key or values as input parameters
Localization support
Extendable via Macros
Created by Ben Sampson
Guide
Installation
Migrate to Native PHP Enums
Enum Library
Basic Usage
Enum Definition
Instantiation
Instance Properties
Instance Casting
Instance Equality
Type Hinting
Flagged/Bitwise Enum
Attribute Casting
Migrations
Validation
Localization
Customizing Descriptions
Customizing Class Description
Customizing Value Descriptions
Extending the Enum Base Class
Laravel Nova Integration
PHPStan Integration
Artisan Command List
Enum Class Reference
Stubs
You are reading the documentation for 6.x
.
If you're using Laravel 8 please see the docs for 4.x
.
If you're using Laravel 7 please see the docs for 2.x
.
If you're using Laravel 6 or below, please see the docs for 1.x
.
Please see the upgrade guide for information on how to upgrade to the latest version.
I wrote a blog post about using laravel-enum: https://sampo.co.uk/blog/using-enums-in-laravel
Requires PHP 8, and Laravel 9 or 10.
composer require bensampo/laravel-enum
PHP 8.1 supports enums natively.
You can migrate your usages of BenSampoEnumEnum
to native PHP enums using the following steps.
Make sure you meet the following requirements:
PHP 8.1 or higher
Laravel 10 or higher
Rector 0.17 or higher, your rector.php
includes all relevant files
Latest version of this library
Depending on the size of your project, you may choose to migrate all enums at once, or migrate just a couple or one enum at a time.
Convert all enums at once: php artisan enum:to-native
Pass the fully qualified class name of an enum to limit the conversion: php artisan enum:to-native "AppEnumsUserType"
This is necessary if any enums are used during the bootstrap phase of Laravel, the conversion of their usages interferes with Larastan and prevents a second run of Rector from working.
Review and validate the code changes for missed edge cases:
See Unimplemented
Enum::coerce()
: If only values were passed, you can replace it with tryFrom()
.
If keys or instances could also be passed, you might need additional logic to cover this.
Enum::$description
and Enum::getDescription()
: Implement an alternative.
try/catch-blocks that handle BenSampoEnumExceptionsInvalidEnumKeyException
or BenSampoEnumExceptionsInvalidEnumMemberException
.
Either catch the ValueError
thrown by native enums, or switch to using tryFrom()
and handle null
.
Once all enums are converted, you can remove your dependency on this library.
Browse and download from a list of commonly used, community contributed enums.
Enum library →
You can use the following Artisan command to generate a new enum class:
php artisan make:enum UserType
Now, you just need to add the possible values your enum can have as constants.
<?php declare(strict_types=1);namespace AppEnums;use BenSampoEnumEnum;final class UserType extends Enum {const Administrator = 0;const Moderator = 1;const Subscriber = 2;const SuperAdministrator = 3; }
That's it! Note that because the enum values are defined as plain constants, you can simply access them like any other class constant.
UserType::Administrator // Has a value of 0
It can be useful to instantiate enums in order to pass them between functions with the benefit of type hinting.
Additionally, it's impossible to instantiate an enum with an invalid value, therefore you can be certain that the passed value is always valid.
For convenience, enums can be instantiated in multiple ways:
// Standard new PHP class, passing the desired enum value as a parameter$enumInstance = new UserType(UserType::Administrator);// Same as the constructor, instantiate by value$enumInstance = UserType::fromValue(UserType::Administrator);// Use an enum key instead of its value$enumInstance = UserType::fromKey('Administrator');// Statically calling the key name as a method, utilizing __callStatic magic$enumInstance = UserType::Administrator();// Attempt to instantiate a new Enum using the given key or value. Returns null if the Enum cannot be instantiated.$enumInstance = UserType::coerce($someValue);
If you want your IDE to autocomplete the static instantiation helpers, you can generate PHPDoc annotations through an artisan command.
By default, all Enums in app/Enums
will be annotated (you can change the folder by passing a path to --folder
).
php artisan enum:annotate
You can annotate a single class by specifying the class name.
php artisan enum:annotate "AppEnumsUserType"
Once you have an enum instance, you can access the key
, value
and description
as properties.
$userType = UserType::fromValue(UserType::SuperAdministrator);$userType->key; // SuperAdministrator$userType->value; // 3$userType->description; // Super Administrator
This is particularly useful if you're passing an enum instance to a blade view.
Enum instances can be cast to strings as they implement the __toString()
magic method.
This also means they can be echoed in blade views, for example.
$userType = UserType::fromValue(UserType::SuperAdministrator); (string) $userType // '3'
You can check the equality of an instance against any value by passing it to the is
method.
For convenience, there is also an isNot
method which is the exact reverse of the is
method.
$admin = UserType::Administrator();$admin->is(UserType::Administrator); // true$admin->is($admin); // true$admin->is(UserType::Administrator()); // true$admin->is(UserType::Moderator); // false$admin->is(UserType::Moderator()); // false$admin->is('random-value'); // false
You can also check to see if the instance's value matches against an array of possible values using the in
method,
and use notIn
to check if instance value is not in an array of values.
Iterables can also be checked against.
$admin = UserType::Administrator();$admin->in([UserType::Moderator, UserType::Administrator]); // true$admin->in([UserType::Moderator(), UserType::Administrator()]); // true$admin->in([UserType::Moderator, UserType::Subscriber]); // false$admin->in(['random-value']); // false$admin->notIn([UserType::Moderator, UserType::Administrator]); // false$admin->notIn([UserType::Moderator(), UserType::Administrator()]); // false$admin->notIn([UserType::Moderator, UserType::Subscriber]); // true$admin->notIn(['random-value']); // true
The instantiated enums are not singletons, rather a new object is created every time.
Thus, strict comparison ===
of different enum instances will always return false
, no matter the value.
In contrast, loose comparison ==
will depend on the value.
$admin = UserType::Administrator();$admin === UserType::Administrator(); // falseUserType::Administrator() === UserType::Administrator(); // false$admin === UserType::Moderator(); // false$admin === $admin; // true$admin == UserType::Administrator(); // true$admin == UserType::Administrator; // true$admin == UserType::Moderator(); // false$admin == UserType::Moderator; // false
One of the benefits of enum instances is that it enables you to use type hinting, as shown below.
function canPerformAction(UserType $userType) {if ($userType->is(UserType::SuperAdministrator)) {return true; }return false; }$userType1 = UserType::fromValue(UserType::SuperAdministrator);$userType2 = UserType::fromValue(UserType::Moderator);canPerformAction($userType1); // Returns truecanPerformAction($userType2); // Returns false
Standard enums represent a single value at a time, but flagged or bitwise enums are capable of of representing multiple values simultaneously. This makes them perfect for when you want to express multiple selections of a limited set of options. A good example of this would be user permissions where there are a limited number of possible permissions but a user can have none, some or all of them.
You can create a flagged enum using the following artisan command:
php artisan make:enum UserPermissions --flagged
When defining values you must use powers of 2, the easiest way to do this is by using the shift left <<
operator like so:
final class UserPermissions extends FlaggedEnum {const ReadComments = 1 << 0;const WriteComments = 1 << 1;const EditComments = 1 << 2;const DeleteComments = 1 << 3;// The next one would be `1 << 4` and so on...}
You can use the bitwise or |
to set a shortcut value which represents a given set of values.
final class UserPermissions extends FlaggedEnum {const ReadComments = 1 << 0;const WriteComments = 1 << 1;const EditComments = 1 << 2;const DeleteComments = 1 << 3;// Shortcutsconst Member = self::ReadComments | self::WriteComments; // Read and write.const Moderator = self::Member | self::EditComments; // All the permissions a Member has, plus Edit.const Admin = self::Moderator | self::DeleteComments; // All the permissions a Moderator has, plus Delete.}
There are couple of ways to instantiate a flagged enum:
// Standard new PHP class, passing the desired enum values as an array of values or array of enum instances$permissions = new UserPermissions([UserPermissions::ReadComments, UserPermissions::EditComments]);$permissions = new UserPermissions([UserPermissions::ReadComments(), UserPermissions::EditComments()]);// Static flags method, again passing the desired enum values as an array of values or array of enum instances$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::EditComments]);$permissions = UserPermissions::flags([UserPermissions::ReadComments(), UserPermissions::EditComments()]);
Attribute casting works in the same way as single value enums.
Flagged enums can contain no value at all. Every flagged enum has a pre-defined constant of None
which is comparable to 0
.
UserPermissions::flags([])->value === UserPermissions::None; // True
In addition to the standard enum methods, there are a suite of helpful methods available on flagged enums.
Note: Anywhere where a static property is passed, you can also pass an enum instance.
Set the flags for the enum to the given array of flags.
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);$permissions->flags([UserPermissions::EditComments, UserPermissions::DeleteComments]); // Flags are now: EditComments, DeleteComments.
Add the given flag to the enum
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);$permissions->addFlag(UserPermissions::EditComments); // Flags are now: ReadComments, EditComments.
Add the given flags to the enum
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);$permissions->addFlags([UserPermissions::EditComments, UserPermissions::WriteComments]); // Flags are now: ReadComments, EditComments, WriteComments.
Add all flags to the enum
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);$permissions->addAllFlags(); // Enum now has all flags
Remove the given flag from the enum
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->removeFlag(UserPermissions::ReadComments); // Flags are now: WriteComments.
Remove the given flags from the enum
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments, UserPermissions::EditComments]);$permissions->removeFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // Flags are now: EditComments.
Remove all flags from the enum
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->removeAllFlags();
Check if the enum has the specified flag.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->hasFlag(UserPermissions::ReadComments); // True$permissions->hasFlag(UserPermissions::EditComments); // False
Check if the enum has all of the specified flags.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->hasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // True$permissions->hasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // False
Check if the enum does not have the specified flag.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->notHasFlag(UserPermissions::EditComments); // True$permissions->notHasFlag(UserPermissions::ReadComments); // False
Check if the enum doesn't have any of the specified flags.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->notHasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // True$permissions->notHasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // False
Return the flags as an array of instances.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->getFlags(); // [UserPermissions::ReadComments(), UserPermissions::WriteComments()];
Check if there are multiple flags set on the enum.
$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);$permissions->hasMultipleFlags(); // True;$permissions->removeFlag(UserPermissions::ReadComments)->hasMultipleFlags(); // False
Get the bitmask for the enum.
UserPermissions::Member()->getBitmask(); // 11;UserPermissions::Moderator()->getBitmask(); // 111;UserPermissions::Admin()->getBitmask(); // 1111;UserPermissions::DeleteComments()->getBitmask(); // 1000;
To use flagged enums directly in your Eloquent queries, you may use the QueriesFlaggedEnums
trait on your model which provides you with the following methods:
User::hasFlag('permissions', UserPermissions::DeleteComments())->get();
User::notHasFlag('permissions', UserPermissions::DeleteComments())->get();
User::hasAllFlags('permissions', [UserPermissions::EditComment(), UserPermissions::ReadComment()])->get();
User::hasAnyFlags('permissions', [UserPermissions::DeleteComments(), UserPermissions::EditComments()])->get();
You may cast model attributes to enums using Laravel's built in custom casting. This will cast the attribute to an enum instance when getting and back to the enum value when setting.
Since Enum::class
implements the Castable
contract, you just need to specify the classname of the enum:
use BenSampoEnumTestsEnumsUserType;use IlluminateDatabaseEloquentModel;class Example extends Model {protected $casts = ['random_flag' => 'boolean', // Example standard laravel cast'user_type' => UserType::class, // Example enum cast]; }
Now, when you access the user_type
attribute of your Example
model,
the underlying value will be returned as a UserType
enum.
$example = Example::first();$example->user_type // Instance of UserType
Review the methods and properties available on enum instances to get the most out of attribute casting.
You can set the value by either passing the enum value or another enum instance.
$example = Example::first();// Set using enum value$example->user_type = UserType::Moderator;// Set using enum instance$example->user_type = UserType::Moderator();
$model->toArray()
behaviourWhen using toArray
(or returning model/models from your controller as a response) Laravel will call the toArray
method on the enum instance.
By default, this will return only the value in its native type. You may want to also have access to the other properties (key, description), for example to return to javascript app.
To customise this behaviour, you can override the toArray
method on the enum instance.
// Example Enumfinal class UserType extends Enum {const ADMINISTRATOR = 0;const MODERATOR = 1; }$instance = UserType::Moderator();// Defaultpublic function toArray() {return $this->value; }// Returns int(1)// Return all propertiespublic function toArray() {return $this; }// Returns an array of all the properties// array(3) {// ["value"]=>// int(1)"// ["key"]=>// string(9) "MODERATOR"// ["description"]=>// string(9) "Moderator"// }
Many databases return everything as strings (for example, an integer may be returned as the string '1'
).
To reduce friction for users of the library, we use type coercion to figure out the intended value. If you'd prefer to control this, you can override the parseDatabase
static method on your enum class:
final class UserType extends Enum {const Administrator = 0;const Moderator = 1;public static function parseDatabase($value) {return (int) $value; } }
Returning null
from the parseDatabase
method will cause the attribute on the model to also be null
. This can be useful if your database stores inconsistent blank values such as empty strings instead of NULL
.
If you're casting attributes on your model to enums, the laravel-ide-helper package can be used to automatically generate property docblocks for you.
Because enums enforce consistency at the code level it's not necessary to do so again at the database level, therefore the recommended type for database columns is string
or int
depending on your enum values. This means you can add/remove enum values in your code without worrying about your database layer.
use AppEnumsUserType;use IlluminateSupportFacadesSchema;use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class CreateUsersTable extends Migration {/** * Run the migrations. * * @return void */public function up(): void{ Schema::table('users', function (Blueprint $table): void {$table->bigIncrements('id');$table->timestamps();$table->string('type') ->default(UserType::Moderator); }); } }
enum
column typeAlternatively you may use Enum
classes in your migrations to define enum columns.
The enum values must be defined as strings.
use AppEnumsUserType;use IlluminateSupportFacadesSchema;use IlluminateDatabaseSchemaBlueprint;use IlluminateDatabaseMigrationsMigration;class CreateUsersTable extends Migration {/** * Run the migrations. * * @return void */public function up(): void{ Schema::table('users', function (Blueprint $table): void {$table->bigIncrements('id');$table->timestamps();$table->enum('type', UserType::getValues()) ->default(UserType::Moderator); }); } }
You may validate that an enum value passed to a controller is a valid value for a given enum by using the EnumValue
rule.
use BenSampoEnumRulesEnumValue;public function store(Request $request) {$this->validate($request, ['user_type' => ['required', new EnumValue(UserType::class)], ]); }
By default, type checking is set to strict, but you can bypass this by passing false
to the optional second parameter of the EnumValue class.
new EnumValue(UserType::class, false) // Turn off strict type checking.
You can also validate on keys using the EnumKey
rule. This is useful if you're taking the enum key as a URL parameter for sorting or filtering for example.
use BenSampoEnumRulesEnumKey;public function store(Request $request) {$this->validate($request, ['user_type' => ['required', new <span class="pl-v"