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

laravel-enum

> 后端框架
Open source

Laravel package to supercharge enum functionalities.

189 stars0 likes0 views
WebsiteGitHub

About

Laravel package to supercharge enum functionalities.

Laravel Enum

[![Author][ico-author]][link-author] [![PHP Version][ico-php]][link-php] [![Laravel Version][ico-laravel]][link-laravel] [![Latest Version][ico-version]][link-packagist] ![Software License][ico-license] [![Build Status][ico-actions]][link-actions] [![Code Quality][ico-code-quality]][link-code-quality] [![Coverage][ico-coverage]][link-coverage] [![PHPStan Level][ico-phpstan]][link-phpstan] [![Total Downloads][ico-downloads]][link-downloads]

Laravel package to supercharge enum functionalities.

[!TIP] Need a framework-agnostic solution? Consider using Enum instead.

Install

Via Composer:

bash
composer require cerbero/laravel-enum

Usage

  • ️ Meta
  • Cases collection
  • Magic translation
  • Encapsulation
    • ️ Cache
    • Session
  • Artisan commands
    • ️ enum:annotate
    • ️ enum:make
    • enum:ts

This package provides all the functionalities of Enum plus Laravel-specific features.

To supercharge our enums, we just need to let them use the Enumerates trait:

php
use Cerbero\LaravelEnum\Concerns\Enumerates;

enum Numbers: int
{
    use Enumerates;

    case One = 1;
    case Two = 2;
    case Three = 3;
}

️ Meta

Laravel Enum extends Enum's meta by allowing us to attach meta with a class name. This class is resolved by the Laravel container when invoking the corresponding meta method:

php
use Cerbero\Enum\Attributes\Meta;

enum PayoutStatuses
{
    use Enumerates;

    #[Meta(handler: SentPayoutHandler::class)]
    case Sent;

    #[Meta(handler: OnHoldPayoutHandler::class)]
    case OnHold;

    #[Meta(handler: DeclinedPayoutHandler::class)]
    case Declined;
}

In the enum above, each case specifies a handler meta with a class name. When a case calls its handler() meta method, the corresponding class is resolved through the IoC container:

php
//  instead of this
$handler = match ($payout->status) {
    PayoutStatuses::Sent => SentPayoutHandler::class,
    PayoutStatuses::OnHold => OnHoldPayoutHandler::class,
    PayoutStatuses::Declined => DeclinedPayoutHandler::class,
};

return Container::getInstance()->make($handler);

//  we can do this
return $payout->status->handler();

If we need to resolve a default class for most cases, we can attach the meta to the enum itself. Cases with their own meta override the default class:

php
use Cerbero\Enum\Attributes\Meta;

#[Meta(handler: DefaultPayoutHandler::class)]
enum PayoutStatuses
{
    use Enumerates;

    #[Meta(handler: SentPayoutHandler::class)]
    case Sent;

    case OnHold;

    case Declined;
}

In the example above, all cases calling the handler() method resolve the DefaultPayoutHandler class, except for the Sent case that resolves SentPayoutHandler.

If the class to be resolved is callable (i.e. it implements the __invoke() method), that class will be both resolved and executed:

php
use Cerbero\Enum\Attributes\Meta;

enum PayoutStatuses
{
    use Enumerates;

    #[Meta(handlePayout: SentPayoutHandler::class)]
    case Sent;

    #[Meta(handlePayout: OnHoldPayoutHandler::class)]
    case OnHold;

    #[Meta(handlePayout: DeclinedPayoutHandler::class)]
    case Declined;
}

In the enum above, each case specifies a handlePayout meta with a callable class. Calling handlePayout() resolves and invokes the class with any passed parameters.

php
//  instead of this
$handler = match ($payout->status) {
    PayoutStatuses::Sent => SentPayoutHandler::class,
    PayoutStatuses::OnHold => OnHoldPayoutHandler::class,
    PayoutStatuses::Declined => DeclinedPayoutHandler::class,
};

$handlePayout = Container::getInstance()->make($handler);

return $handlePayout($payout);

//  we can do this
return $payout->status->handlePayout($payout);

If we need to run a default callable class for most cases, we can attach the meta to the enum itself. Cases with their own meta override the default callable class:

php
use Cerbero\Enum\Attributes\Meta;

#[Meta(handlePayout: DefaultPayoutHandler::class)]
enum PayoutStatuses
{
    use Enumerates;

    #[Meta(handlePayout: SentPayoutHandler::class)]
    case Sent;

    case OnHold;

    case Declined;
}

In the example above, all cases calling the handlePayout() method execute the DefaultPayoutHandler class, except for the Sent case, which runs the SentPayoutHandler.

[!TIP] Our IDE can autocomplete meta methods thanks to the enum:annotate command.

Class names in meta are annotated by identifying the common interface or parent class they share.

Cases collection

The original cases collection has been extended for better integration with the Laravel framework.

The new cases collection implements the Illuminate\Contracts\Support\Arrayable and Illuminate\Contracts\Support\Jsonable contracts and it can be serialized into a JSON.

It also leverages the following Laravel traits:

  • Illuminate\Support\Traits\Conditionable for conditional chaining of methods
  • Illuminate\Support\Traits\Macroable for adding methods to the collection at runtime
  • Illuminate\Support\Traits\Tappable for running custom logic while keeping method chaining

Additionally, the new collection enables us to dump() and dd() its cases:

php
Numbers::collect()->dump();

Numbers::collect()->dd();

Cases collection can be cast in an Eloquent model to store multiple cases in a single database column and then re-hydrate those cases back into a collection:

php
use Cerbero\LaravelEnum\CasesCollection;

class User extends Model
{
    // before Laravel 11
    protected $casts = [
        'numbers' => CasesCollection::class . ':' . Numbers::class,
    ];

    // after Laravel 11
    protected function casts(): array
    {
        return [
            'numbers' => CasesCollection::of(Numbers::class),
        ];
    }
}

Once the cast is set, we can assign an array of names, values or cases to the cast property of the model and receive a cases collection when accessing the property:

php
$user->numbers = ['One', 'Two'];

$user->numbers = [1, 2];

$user->numbers = [Numbers::One, Numbers::Two];

$user->numbers; // CasesCollection[Numbers::One, Numbers::Two]

The cases collection above is stored in the database as ["One","Two"] for a pure enum, or as [1,2] for a backed enum.

The cast also supports bitwise backed enums, so for instance, if we have a Permissions enum implementing the Bitwise contract:

php
use Cerbero\LaravelEnum\Contracts\Bitwise;

enum Permissions: int implements Bitwise
{
    use Enumerates;

    case CreatePost = 1;
    case UpdatePost = 2;
    case DeletePost = 4;
}

and we cast the permissions property in our Eloquent model:

php
use Cerbero\LaravelEnum\CasesCollection;

class User extends Model
{
    // before Laravel 11
    protected $casts = [
        'permissions' => CasesCollection::class . ':' . Permissions::class,
    ];

    // after Laravel 11
    protected function casts(): array
    {
        return [
            'permissions' => CasesCollection::of(Permissions::class),
        ];
    }
}

we can assign a bitwise value or an array of bitwise values/cases to the permissions property and receive a cases collection in return:

php
$user->permissions = 3;

$user->permissions = 1 | 2;

$user->permissions = Permissions::CreatePost->value | Permissions::UpdatePost->value;

$user->permissions = [1, 2];

$user->permissions = [Permissions::CreatePost, Permissions::UpdatePost];

$user->permissions; // CasesCollection[Permissions::CreatePost, Permissions::UpdatePost]

The cases collection above is stored in the database as 3, the result of the OR bitwise operator.

Magic translation

On top of Enum's magic, when a case calls an inaccessible method without a corresponding meta match, Laravel Enum assumes that we want to access a translation:

php
Numbers::One->description();

// lang/en/enums.php
return [
    Numbers::class => [
        'One' => [
            'description' => 'This is the case One.',
        ],
    ],
];

By default the translation key is resolved as enums.{enum namespace}.{case name}.{inaccessible method}. If customization is needed, we can adjust the translation key:

php
use Cerbero\LaravelEnum\Enums;

Enums::translateFrom(function(UnitEnum $case, string $method) {
    return sprintf('custom.%s.%s.%s', $case::class, $case->name, $method);
});

The above logic will resolve the translation key as custom.{enum namespace}.{case name}.{inaccessible method}.

Additionally, we can pass named arguments to replace placeholders within our translations:

php
return [
    Numbers::class => [
        'One' => [
            'description' => 'This is the case :value.',
        ],
    ],
];

// This is the case 1.
Numbers::One->description(value: 1);

Translations are accessible through enum operations as well:

php
$options = Numbers::pluck('description', 'value');

/*
[
    1 => 'This is the case One.',
    2 => 'This is the case Two.',
    3 => 'This is the case Three.',
]
*/

[!TIP] Our IDE can autocomplete translation methods thanks to the enum:annotate command.

Encapsulation

Laravel Enum offers extra traits to encapsulate Laravel features that deal with keys. By defining keys as enum cases, we can leverage Laravel features without having to remember or repeat such keys.

The benefits of this approach are many:

  • avoiding scattered, error-prone strings throughout the codebase
  • preventing key misspellings
  • enabling IDE autocompletion
  • reviewing all application keys in a central location
  • updating keys in one place rather than replacing all instances

️ Cache

To encapsulate the Laravel cache, we can define a backed enum with all our cache keys and apply the EnumeratesCacheKeys trait:

php
use Cerbero\LaravelEnum\Concerns\EnumeratesCacheKeys;

enum CacheKeys: string
{
    use EnumeratesCacheKeys;

    case PostComments = 'posts.{int $postId}.comments';
    case Tags = 'tags';
    case TeamMemberPosts = 'teams.{string $teamId}.users.{string $userId}.posts';
}

The EnumeratesCacheKeys trait incorporates Enumerates, hence all the features of this package. We can now leverage all the Laravel cache methods by statically calling enum cases:

…

When calling cases statically, we can pass parameters to resolve dynamic keys. Such parameters replace the {...} placeholders in the cache keys:

php
CacheKeys::TeamMemberPosts($teamId, $userId)->exists();

Session

To encapsulate the Laravel session, we can define a backed enum with all our session keys and apply the EnumeratesSessionKeys trait:

php
use Cerbero\LaravelEnum\Concerns\EnumeratesSessionKeys;

enum SessionKeys
{
    use EnumeratesSessionKeys;

    case CartItems = 'cart-items';
    case OnboardingStep = 'onboarding-step';
    case FormsData = 'forms.{int $formId}.data';
}

The EnumeratesSessionKeys trait incorporates Enumerates, hence all the features of this package. We can now leverage all the Laravel session methods by statically calling enum cases:

…

When calling cases statically, we can pass parameters to resolve dynamic keys. Such parameters replace the {...} placeholders in the session keys:

php
SessionKeys::FormsData($formId)->exists();

[!TIP]

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPenumenumerationlaravel

No comments yet. Be the first to share.

> Details

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

> Related tools

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