Download the PHP package bensampo/laravel-enum without Composer
On this page you can find all versions of the php package bensampo/laravel-enum. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download bensampo/laravel-enum
More information about bensampo/laravel-enum
Files in bensampo/laravel-enum
Package laravel-enum
Short Description Simple, extensible and powerful enumeration implementation for Laravel.
License MIT
Homepage https://github.com/bensampo/laravel-enum
Informations about the package laravel-enum
Using this library is no longer recommended
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.
About Laravel Enum
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
Jump To
- 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
Documentation for older versions
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.
Guide
I wrote a blog post about using laravel-enum: https://sampo.co.uk/blog/using-enums-in-laravel
Installation
Requires PHP 8, and Laravel 9 or 10.
Migrate to Native PHP Enums
PHP 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:
- 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 "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:
- See Unimplemented
Enum::coerce()
: If only values were passed, you can replace it withtryFrom()
. If keys or instances could also be passed, you might need additional logic to cover this.Enum::$description
andEnum::getDescription()
: Implement an alternative.- try/catch-blocks that handle
BenSampo\Enum\Exceptions\InvalidEnumKeyException
orBenSampo\Enum\Exceptions\InvalidEnumMemberException
. Either catch theValueError
thrown by native enums, or switch to usingtryFrom()
and handlenull
.
Once all enums are converted, you can remove your dependency on this library.
Enum Library
Browse and download from a list of commonly used, community contributed enums.
Enum library →
Basic Usage
Enum Definition
You can use the following Artisan command to generate a new enum class:
Now, you just need to add the possible values your enum can have as constants.
That's it! Note that because the enum values are defined as plain constants, you can simply access them like any other class constant.
Instantiation
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:
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
).
You can annotate a single class by specifying the class name.
Instance Properties
Once you have an enum instance, you can access the key
, value
and description
as properties.
This is particularly useful if you're passing an enum instance to a blade view.
Instance Casting
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.
Instance Equality
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.
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.
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.
Type Hinting
One of the benefits of enum instances is that it enables you to use type hinting, as shown below.
Flagged/Bitwise Enum
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
Defining values
When defining values you must use powers of 2, the easiest way to do this is by using the shift left <<
operator like so:
Defining shortcuts
You can use the bitwise or |
to set a shortcut value which represents a given set of values.
Instantiating a flagged enum
There are couple of ways to instantiate a flagged enum:
Attribute casting works in the same way as single value enums.
Empty flagged enums
Flagged enums can contain no value at all. Every flagged enum has a pre-defined constant of None
which is comparable to 0
.
Flagged enum methods
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.
setFlags(array $flags): Enum
Set the flags for the enum to the given array of flags.
addFlag($flag): Enum
Add the given flag to the enum
addFlags(array $flags): Enum
Add the given flags to the enum
addAllFlags(): Enum
Add all flags to the enum
removeFlag($flag): Enum
Remove the given flag from the enum
removeFlags(array $flags): Enum
Remove the given flags from the enum
removeAllFlags(): Enum
Remove all flags from the enum
hasFlag($flag): bool
Check if the enum has the specified flag.
hasFlags(array $flags): bool
Check if the enum has all of the specified flags.
notHasFlag($flag): bool
Check if the enum does not have the specified flag.
notHasFlags(array $flags): bool
Check if the enum doesn't have any of the specified flags.
getFlags(): Enum[]
Return the flags as an array of instances.
hasMultipleFlags(): bool
Check if there are multiple flags set on the enum.
getBitmask(): int
Get the bitmask for the enum.
Flagged enums in Eloquent queries
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:
hasFlag($column, $flag): Builder
notHasFlag($column, $flag): Builder
hasAllFlags($column, $flags): Builder
hasAnyFlags($column, $flags): Builder
Attribute Casting
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:
Now, when you access the user_type
attribute of your Example
model,
the underlying value will be returned as a UserType
enum.
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.
Customising $model->toArray()
behaviour
When 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.
Casting underlying native types
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:
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
.
Model Annotation
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.
Migrations
Recommended
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.
Using enum
column type
Alternatively you may use Enum
classes in your migrations to define enum columns.
The enum values must be defined as strings.
Validation
Array Validation
Enum value
You may validate that an enum value passed to a controller is a valid value for a given enum by using the EnumValue
rule.
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.
Enum key
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.
Enum instance
Additionally you can validate that a parameter is an instance of a given enum.
Pipe Validation
You can also use the 'pipe' syntax for rules.
enum_value_:enumclass,[strict]
enum_key_:enumclass
enum_:enumclass
Localization
Validation messages
Run the following command to publish the language files to your lang
folder.
Enum descriptions
You can translate the strings returned by the getDescription
method using Laravel's built-in localization features.
Add a new enums.php
keys file for each of your supported languages. In this example there is one for English and one for Spanish.
Now, you just need to make sure that your enum implements the LocalizedEnum
interface as demonstrated below:
The getDescription
method will now look for the value in your localization files. If a value doesn't exist for a given key, the default description is returned instead.
Customizing descriptions
Customizing class description
If you'd like to return a custom description for your enum class, add a Description
attribute to your Enum class:
Calling UserType::getClassDescription()
now returns List of available User types
instead of User type
.
You may also override the getClassDescription
method on the base Enum class if you wish to have more control of the description.
Customizing value descriptions
If you'd like to return a custom description for your enum values, add a Description
attribute to your Enum constants:
Calling UserType::SuperAdministrator()->description
now returns Super admin
instead of Super administrator
.
You may also override the getDescription
method on the base Enum class if you wish to have more control of the description.
Extending the Enum Base Class
The Enum
base class implements the Laravel Macroable
trait, meaning it's easy to extend it with your own functions. If you have a function that you often add to each of your enums, you can use a macro.
Let's say we want to be able to get a flipped version of the enum asArray
method, we can do this using:
Now, on each of my enums, I can call it using UserType::asFlippedArray()
.
It's best to register the macro inside a service providers' boot method.
Laravel Nova Integration
Use the nova-enum-field package by Simple Squid to easily create fields for your Enums in Nova. See their readme for usage.
PHPStan Integration
If you are using PHPStan for static analysis, enable the extension for:
- proper recognition of the magic instantiation methods
- detection of duplicate enum values
Use PHPStan Extension Installer or add the following to your projects phpstan.neon
includes:
Artisan Command List
php artisan make:enum
Create a new enum class. Pass --flagged
as an option to create a flagged enum.
Find out more
php artisan enum:annotate
Generate DocBlock annotations for enum classes.
Find out more
php artisan enum:to-native
See migrate to native PHP enums.
Enum Class Reference
static getKeys(mixed $values = null): array
Returns an array of all or a custom set of the keys for an enum.
static getValues(mixed $keys = null): array
Returns an array of all or a custom set of the values for an enum.
static getKey(mixed $value): string
Returns the key for the given enum value.
static getValue(string $key): mixed
Returns the value for the given enum key.
static hasKey(string $key): bool
Check if the enum contains a given key.
static hasValue(mixed $value, bool $strict = true): bool
Check if the enum contains a given value.
static getClassDescription(): string
Returns the class name in sentence case for the enum class. It's possible to customize the description if the guessed description is not appropriate.
static getDescription(mixed $value): string
Returns the key in sentence case for the enum value. It's possible to customize the description if the guessed description is not appropriate.
static getRandomKey(): string
Returns a random key from the enum. Useful for factories.
static getRandomValue(): mixed
Returns a random value from the enum. Useful for factories.
static getRandomInstance(): mixed
Returns a random instance of the enum. Useful for factories.
static asArray(): array
Returns the enum key value pairs as an associative array.
static asSelectArray(): array
Returns the enum for use in a select as value => description.
static fromValue(mixed $enumValue): Enum
Returns an instance of the called enum. Read more about enum instantiation.
static getInstances(): array
Returns an array of all possible instances of the called enum, keyed by the constant names.
static coerce(mixed $enumKeyOrValue): ?Enum
Attempt to instantiate a new Enum using the given key or value. Returns null if the Enum cannot be instantiated.
Stubs
Run the following command to publish the stub files to the stubs
folder in the root of your application.
All versions of laravel-enum with dependencies
composer/class-map-generator Version ^1
illuminate/contracts Version ^9 || ^10 || ^11
illuminate/support Version ^9 || ^10 || ^11
laminas/laminas-code Version ^3.4 || ^4
nikic/php-parser Version ^4.13.2 || ^5