Simple, extensible and powerful enumeration implementation for Laravel.
Simple, extensible and powerful enumeration implementation for Laravel.
Using this library is no longer recommended, especially for new projects. PHP 8.1 supports enums natively.
See https://github.com/BenSampo/laravel-enum/issues/332.
Simple, extensible and powerful enumeration implementation for Laravel.
Created by Ben Sampson
You are reading the documentation for 6.x.
4.x.2.x.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 through 13.
composer require bensampo/laravel-enumPHP 8.1 supports enums natively.
You can migrate your usages of BenSampo\Enum\Enum to native PHP enums using the following steps.
Make sure you meet the following requirements:
rector.php includes all relevant filesDepending 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 "App\Enums\UserType"
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:
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.BenSampo\Enum\Exceptions\InvalidEnumKeyException or BenSampo\Enum\Exceptions\InvalidEnumMemberException.
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.
You can use the following Artisan command to generate a new enum class:
php artisan make:enum UserTypeNow, you just need to add the possible values your enum can have as constants.
<?php declare(strict_types=1);
namespace App\Enums;
use BenSampo\Enum\Enum;
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 0It 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:
…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:annotateYou can annotate a single class by specifying the class name.
php artisan enum:annotate "App\Enums\UserType"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 AdministratorThis 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'); // falseYou 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.
…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(); // false
UserType::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; // falseOne 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 true
canPerformAction($userType2); // Returns falseStandard 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;
// Shortcuts
const 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:
…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; // TrueIn 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 flagsRemove the given flag from the enum
$permissions = UserPermissions::flags([UserPermissNo open issues yet, or sync has not completed.