Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-enum

> 后端框架
Open source

Simple, extensible and powerful enumeration implementation for Laravel.

2.0K stars0 likes1 views
WebsiteGitHub

About

Simple, extensible and powerful enumeration implementation for Laravel.

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 through 13.

bash
composer require bensampo/laravel-enum

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 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 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.

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:

php
php artisan make:enum UserType

Now, you just need to add the possible values your enum can have as constants.

php
<?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.

php
UserType::Administrator // Has a value of 0

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).

bash
php artisan enum:annotate

You can annotate a single class by specifying the class name.

bash
php artisan enum:annotate "App\Enums\UserType"

Instance Properties

Once you have an enum instance, you can access the key, value and description as properties.

php
$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.

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.

php
$userType = UserType::fromValue(UserType::SuperAdministrator);

(string) $userType // '3'

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.

php
$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.

…

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.

php
$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;       // false

Type Hinting

One of the benefits of enum instances is that it enables you to use type hinting, as shown below.

php
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 false

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:

php
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...
}

Defining shortcuts

You can use the bitwise or | to set a shortcut value which represents a given set of values.

php
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.
}

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.

php
UserPermissions::flags([])->value === UserPermissions::None; // True

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.

php
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->flags([UserPermissions::EditComments, UserPermissions::DeleteComments]); // Flags are now: EditComments, DeleteComments.

addFlag($flag): Enum

Add the given flag to the enum

php
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlag(UserPermissions::EditComments); // Flags are now: ReadComments, EditComments.

addFlags(array $flags): Enum

Add the given flags to the enum

php
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addFlags([UserPermissions::EditComments, UserPermissions::WriteComments]); // Flags are now: ReadComments, EditComments, WriteComments.

addAllFlags(): Enum

Add all flags to the enum

php
$permissions = UserPermissions::flags([UserPermissions::ReadComments]);
$permissions->addAllFlags(); // Enum now has all flags

removeFlag($flag): Enum

Remove the given flag from the enum

php
$permissions = UserPermissions::flags([UserPermiss

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPbitwise-enumenumenum-instantiationenum-library

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架