PHPackages                             reafeichtinger/laravel-enums-plus - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. reafeichtinger/laravel-enums-plus

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

reafeichtinger/laravel-enums-plus
=================================

Supercharge your PHP8 enums with powers like localization support and fluent comparison methods.

3.2.0(7mo ago)110MITPHPPHP ^8.1

Since Sep 26Pushed 7mo agoCompare

[ Source](https://github.com/reafeichtinger/laravel-enums-plus)[ Packagist](https://packagist.org/packages/reafeichtinger/laravel-enums-plus)[ Docs](https://github.com/reafeichtinger/laravel-enums-plus)[ RSS](/packages/reafeichtinger-laravel-enums-plus/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (13)Versions (5)Used By (0)

[![Banner Image](https://camo.githubusercontent.com/38eaffc36a89383b109e9c1fc875fee489582725082b71efef80b6329a32baf7/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f4c61726176656c253230456e756d73253230506c75732e706e673f7468656d653d6461726b267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d726561666569636874696e6765722532466c61726176656c2d656e756d732d706c7573267061747465726e3d746f706f677261706879267374796c653d7374796c655f32266465736372697074696f6e3d53757065726368617267652b796f75722b5048502b382e312532422b656e756d732b696e2b4c61726176656c266d643d312673686f7757617465726d61726b3d3026666f6e7453697a653d313030707826696d616765733d68747470732533412532462532466c61726176656c2e636f6d253246696d672532466c6f676f6d61726b2e6d696e2e73766726686569676874733d6175746f)](https://camo.githubusercontent.com/38eaffc36a89383b109e9c1fc875fee489582725082b71efef80b6329a32baf7/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f4c61726176656c253230456e756d73253230506c75732e706e673f7468656d653d6461726b267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d726561666569636874696e6765722532466c61726176656c2d656e756d732d706c7573267061747465726e3d746f706f677261706879267374796c653d7374796c655f32266465736372697074696f6e3d53757065726368617267652b796f75722b5048502b382e312532422b656e756d732b696e2b4c61726176656c266d643d312673686f7757617465726d61726b3d3026666f6e7453697a653d313030707826696d616765733d68747470732533412532462532466c61726176656c2e636f6d253246696d672532466c6f676f6d61726b2e6d696e2e73766726686569676874733d6175746f)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ffec1992f669e469dc1b131a7d942ed0b647a194e5d6acd229c10f4f8327d1dc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726561666569636874696e6765722f6c61726176656c2d656e756d732d706c75732e7376673f7374796c653d666c6174)](https://packagist.org/packages/reafeichtinger/laravel-enums-plus)[![Total Downloads](https://camo.githubusercontent.com/908893cd449b726ea2e7512c1af230d6dd1da895b5e201b20e03f84b027feade/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f726561666569636874696e6765722f6c61726176656c2d656e756d732d706c75732e7376673f7374796c653d666c6174)](https://packagist.org/packages/reafeichtinger/laravel-enums-plus)

This package supercharges your PHP 8.1+ enums with superpowers like localization support and fluent comparison methods.

Installation
============

[](#installation)

```
composer require reafeichtinger/laravel-enums-plus
```

Publishing the config
---------------------

[](#publishing-the-config)

You might want to overwrite some default settings. You can pushlish the config for further editing with this command.

```
php artisan vendor:publish --tag=enums-plus-config
```

Creating a new enum class with the `make:enum` Command
======================================================

[](#creating-a-new-enum-class-with-the-makeenum-command)

Creating a new Laravel Enum is easy with the make:enum command.

Command:
--------

[](#command)

```
php artisan make:enum-plus {name} --string # or --int
```

### Arguments:

[](#arguments)

- `{name}`: The name of the enum class to be created (e.g., OrderStatus). The command will automatically append "Enum" to the name (e.g., OrderStatusEnum).
- `{type?}`: The underlying data type for the enum. Can be either --int --string or if not specified it will be a pure enum.
- `{--force}`: Overwrite the enum if it already exists. Example Usage:

To create an enum named OrderStatusEnum backed by integers:

```
php artisan make:enum OrderStatus --int
```

To create an enum named OrderStatusEnum backed by strings:

```
php artisan make:enum OrderStatus --string
```

To create a pure enum named OrderStatusEnum:

```
php artisan make:enum OrderStatus
```

This will generate an OrderStatusEnums in the `app/Enums` directory.

Upgrading your existing enums
=============================

[](#upgrading-your-existing-enums)

The enum you create must implement the `EnumPlus` interface and also use the `IsEnumPlus` trait. The interface is required for Laravel to cast your enum correctly and the trait is what gives your enum its superpowers.

```
use Rea\LaravelEnumsPlus\EnumPlus;
use Rea\LaravelEnumsPlus\IsEnumPlus;

enum VolumeUnitEnum: string implements EnumPlus // Add this
{
    use IsEnumPlus; // Add this

    case MILLIGRAMS = "milligrams";
    case GRAMS = "grams";
    case KILOGRAMS = "kilograms";
    case TONNE = "tonne";
}
```

Enhance your enum class
=======================

[](#enhance-your-enum-class)

Once you have your basic enum class you can enhance and customize it so it fits your project.

Enum value labels (Localization)
--------------------------------

[](#enum-value-labels-localization)

All translations support pluralization as well as placeholders but in some cases you cannot specify the count or the placeholders. In order to have control over the default values in this case you may define a `defaultCount` and `defaultReplace` method.

```
public function defaultCount(): int
{
    return 0; // Would be 1 by default
}

public function defaultReplace(): array
{
    return [
        'of' => "butter", // Would be an empty array by default
    ];
}
```

### Translations directly in the enum

[](#translations-directly-in-the-enum)

You can define translations directly inside of the enum class by adding a `translation` method:

```
public function translations(): array
{
    return [
        'en' => [
            self::GRAMS->value => ':count gram of :of|:count grams of :of',
            self::MILLIGRAMS->value => ':count milligram of :of|:count milligrams of :of',
            self::KILOGRAMS->value => ':count kilogram of :of|:count kilograms of :of',
            self::TONNE->value => ':count tonne of :of|:count tonnes of :of',
        ],
        'de' => [
            self::GRAMS->value => ':count Gram :Of|:count Gram :Of',
            self::MILLIGRAMS->value => ':count Milligram :Of|:count Milligram :Of',
            self::KILOGRAMS->value => ':count Kilogram :Of|:count Kilogram :Of',
            self::TONNE->value => ':count Tonne :Of|:count Tonnen :Of',
        ],
    ];
}
```

If you do not specify a `translations` method, it will fallback to the enums.php translation file.

### Using laravel translations

[](#using-laravel-translations)

Create `enums.php` lang file and create labels for your enum values.

> **Note:**The path to the enum translations can be customized via the config file.

```
// resources/lang/en/enums.php

return [
     VolumeUnitEnum::class => [
        VolumeUnitEnum::MILLIGRAMS->value => "mg",
        VolumeUnitEnum::GRAMS->value      => "g",
        VolumeUnitEnum::KILOGRAMS->value  => "kg",
        VolumeUnitEnum::TONNE->value      => "t"
     ]
];
```

You may then access these localized values using the `->label()`, `->trans()`, `::labelFor()` or `::transFor()` methods.
Additionally rendering the enum in a blade template will render the label.

```
VolumeUnitEnum::MILLIGRAMS->label(); // "mg"
VolumeUnitEnum::MILLIGRAMS->trans(); // "mg"
VolumeUnitEnum::labelFor(VolumeUnitEnum::TONNE); // "t"
VolumeUnitEnum::transFor(VolumeUnitEnum::TONNE); // "t"
// in blade
{{ VolumeUnitEnum::KILOGRAMS }} // "kg" - Uses default count and replace values
```

If you do not specify a label in the lang file these methods will return the value assigned to the enum inside the enum file. e.g MILLIGRAMS label will be milligrams.

Meta data
---------

[](#meta-data)

Adding metadata allows you to return additional values alongside the label and values.

Create a withMeta method on your enum to add metadata.

```
public function withMeta(): array
{
    return match ($this) {
        self::MILLIGRAMS                => [
            'background_color' => 'bg-green-100',
            'text_color'       => 'text-green-800',
        ],
        self::GRAMS                     => [
            'background_color' => 'bg-red-100',
            'text_color'       => 'text-red-800',
        ],
        self::KILOGRAMS, self::TONNE    => [
            'background_color' => 'bg-gray-100',
            'text_color'       => 'text-gray-800',
        ],
        default                         => [
            'background_color' => 'bg-blue-100',
            'text_color'       => 'text-blue-800',
        ],
    };
}
```

If you do not specify a `withMeta` method, meta will be an empty array.

Alias
-----

[](#alias)

Adding aliases allows you to match additional values to an enum case.

Create a withAlias method on your enum to add them.

```
public function withAlias(): array
{
    return match ($this) {
        self::MILLIGRAMS    => ['mg'],
        self::GRAMS         => ['g'],
        self::KILOGRAMS     => ['kg'],
        self::TONNE         => ['t', 'ton'],
        default             => [],
    };
}
```

If you do not specify a `withAlias` method, meta will be an empty array.

Other methods
=============

[](#other-methods)

`options()`
-----------

[](#options)

Returns an array of all enum values with their labels and metadata.

### Usage

[](#usage)

```
VolumeUnitEnum::options();
VolumeUnitEnum::optionsC(); // For collection
```

returns

```
[
    [
        'name'  => 'MILLIGRAMS',
        'value' => 'milligrams',
        'label' => 'mg',
        'meta'  => [
            'background_color' => 'bg-green-100',
            'text_color'       => 'text-green-800',
        ],
        'alias' => [
            'mg',
        ]
    ],
    [
        'name'  => 'GRAMS',
        'value' => 'grams',
        'label' => 'g',
        'meta'  => [
            'background_color' => 'bg-red-100',
            'text_color'       => 'text-red-800',
        ],
        'alias' => [
            'g',
        ]
        ...
    ]
]
```

`names()`
---------

[](#names)

Returns an array of all enum names.

### Usage

[](#usage-1)

```
VolumeUnitEnum::names();
VolumeUnitEnum::namesC(); // For collection
```

returns

```
[
    'MILLIGRAMS',
    'GRAMS',
    'KILOGRAMS',
    'TONNE',
]
```

`values()`
----------

[](#values)

Returns an array of all enum values.

### Usage

[](#usage-2)

```
VolumeUnitEnum::values();
VolumeUnitEnum::valuesC(); // For collection
```

returns

```
[
    'milligrams',
    'grams',
    'killograms',
    'tonne',
]
```

`labels()`
----------

[](#labels)

Returns an array of all enum translations.

### Usage

[](#usage-3)

```
VolumeUnitEnum::labels();
VolumeUnitEnum::labelsC(); // For collection
```

returns

```
[
    'mg',
    'g',
    'kg',
    't',
]
```

`dict()`
--------

[](#dict)

Returns an array of all enum values mapping to their label.

### Usage

[](#usage-4)

```
VolumeUnitEnum::dict();
VolumeUnitEnum::dictC(); // For collection
```

returns

```
[
    'MILLIGRAMS' => 'mg',
    'GRAMS'      => 'g',
    'KILOGRAMS'  => 'kg',
    'TONNE'      => 't',
]
```

`toArray()` &amp; `toCollection()`
----------------------------------

[](#toarray--tocollection)

Returns an array or collection of a single enum instance with its label, metadata and alias.

### Usage

[](#usage-5)

```
VolumeUnitEnum::MILLIGRAMS->toArray();
VolumeUnitEnum::MILLIGRAMS->toCollection(); // For collection
```

returns

```
[
    'name'  => 'MILLIGRAMS',
    'value' => 'milligrams',
    'label' => 'mg',
    'meta'  => [
        'color'      => 'bg-green-100',
        'text_color' => 'text-green-800',
    ],
]
```

`toHtml()`
----------

[](#tohtml)

An alias of ::label(). Used to satisfy Laravel's Htmlable interface.

### Usage

[](#usage-6)

```
VolumeUnitEnum::MILLIGRAMS->toHtml();
```

returns

```
mg
```

`toJson()`
----------

[](#tojson)

Returns a json string represention of the `toArray()` return value.

`is()`, `isA()` and `isAn()`
----------------------------

[](#is-isa-and-isan)

Allows you to check if an enum is a given value. Returns a boolean.

> **Note**`isA`, `isAn` are just aliases for `is`.

### Usage

[](#usage-7)

```
VolumeUnitEnum::MILLIGRAMS->is(VolumeUnitEnum::MILLIGRAMS); // true
VolumeUnitEnum::MILLIGRAMS->is('MILLIGRAMS');               // true
VolumeUnitEnum::MILLIGRAMS->is('invalid');                  // false
```

`isNot()`, `isNotA()` and `isNotAn()`
-------------------------------------

[](#isnot-isnota-and-isnotan)

Allows you to check if an enum is not a given value. Returns a boolean.

> **Note**`isNotA` and `isNotAn` are just aliases for `isNot`.

### Usage

[](#usage-8)

```
VolumeUnitEnum::MILLIGRAMS->isNot(VolumeUnitEnum::GRAMS); // true
VolumeUnitEnum::MILLIGRAMS->isNot('GRAMS');               // true
VolumeUnitEnum::MILLIGRAMS->isNot('invalid');             // true
VolumeUnitEnum::MILLIGRAMS->isNot('MILLIGRAMS');          // false
```

`isAny()`
---------

[](#isany)

Allows you to check if an enum is contained in an array. Returns a boolean.

### Usage

[](#usage-9)

```
VolumeUnitEnum::MILLIGRAMS->isAny(['GRAMS', VolumeUnitEnum::TONNE]);                    // false
VolumeUnitEnum::MILLIGRAMS->isAny([VolumeUnitEnum::GRAMS, VolumeUnitEnum::MILLIGRAMS]); // true
```

`isNotAny()`
------------

[](#isnotany)

Allows you to check if an enum is not contained in an array. Returns a boolean.

### Usage

[](#usage-10)

```
VolumeUnitEnum::MILLIGRAMS->isNotAny(['GRAMS', VolumeUnitEnum::TONNE]);                    // true
VolumeUnitEnum::MILLIGRAMS->isNotAny([VolumeUnitEnum::GRAMS, VolumeUnitEnum::MILLIGRAMS]); // false
```

`rule()`
--------

[](#rule)

The enums may be validated using Laravel's standard Enum validation rule - `new Illuminate\Validation\Rules\Enum(VolumeUnitEnum::class)`.
This method a shortcut for the validation rule. It supports specifying excluded cases.

### Usage

[](#usage-11)

```
public function rules(): array
{
    return [
        'volume_unit' => [VolumeUnitEnum::rule()],
    ];
}
```

`matches()`
-----------

[](#matches)

Find all matches and their respective levenshtein distance for a given input string. Can be used to determine what case is the closest match to the input string.

```
VolumeUnitEnum::matches('ton');
```

returns

```
[
    [
        'case' => VolumeUnitEnum::TONNE,
        'distance' => 2,
    ],
]
```

`parse()`
---------

[](#parse)

Allows parsing any string value or enum instance to an enum instance. This method makes use of the `matches()` method in order to find the case with the closest distance. It also takes into account all defined `alias()`.

```
TODO
```

returns

```
TODO
```

`select()`
----------

[](#select)

Highly customizable method to get data for select components.

```
/**
* Parse this enums values into a valid format for select components.
*
* @param  null|string|self|array|Collection  $selected  The currently selected case(s).
* @param  null|string|self|array|Collection  $exclude  What enum case(s) should not be included.
* @param  null|string|Closure  $translation  When null the label() method is used. When a string, it uses the string value as a base translation path. When a closure, the result of the closure will be used.
* @param  string[]|Closure[]  $columns  Any additional columns to add to the result. Strings can be method or property names on the enum, closures will be called and the return value is used.
*/
public static function select(
    null|string|self|array|Collection $selected = null,
    null|string|self|array|Collection $exclude = null,
    null|string|Closure $translation = null,
    string|Closure ...$columns): array
```

The `$selected` parameter determines which value(s) are currently selected. For a single select this is the case value of the enum instance. For a multiselect it is an array of case values of the enum instance.

The `$exclude` parameter should be either null, a string or enum instance or an array or collection of those. The provided case(s) will not be included in the result.

The `$translation` parameter is either a string referring to a method or property on the enum instance or a closure that gets the current string case and returns the actual string that should be used as the label. By default it will load the `label()` of the each enum case.

The `$columns` parameters are either strings referring to a method or property on the enum instance, or closures that should additionally be included in the resulting array data.

Other Classes
=============

[](#other-classes)

AsFullEnumCollection
--------------------

[](#asfullenumcollection)

This cast is similar to the Laravel built in `AsEnumCollection` cast but unlike the built-in will maintain the full `toArray` structure when converting to json.

E.g. the Laravel built in `AsEnumCollection` cast will return the following json:

```
[
    "MILLIGRAMS",
    "GRAMS"
]
```

This cast will return

```
[
    {
        "name": "MILLIGRAMS",
        "value": "MILLIGRAMS",
        "label": "mg",
        "meta": {
            "background_color": "bg-green-100",
            "text_color": "text-green-800"
        },
        "alias": [
            "mg"
        ],
    },
    {
        "name": "GRAMS",
        "value": "GRAMS",
        "label": "g",
        "meta": {
            "background_color": "bg-red-100",
            "text_color": "text-red-800"
        },
        "alias": [
            "g"
        ],
    }
]
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

This project was forked from version v2.6.1 of the foxbytehq/laravel-backed-enums repository, you might want to contribute to or use the base rather than the heavily cusomized version from me.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance64

Regular maintenance activity

Popularity7

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

4

Last Release

221d ago

Major Versions

2.7.0 → 3.0.12025-09-26

### Community

Maintainers

![](https://www.gravatar.com/avatar/c691d24c350185dd773fed5e99f0dee528ef24a7472fb0b073c9163454cb861c?d=identicon)[reafeichtinger](/maintainers/reafeichtinger)

---

Top Contributors

[![hailwood](https://avatars.githubusercontent.com/u/709773?v=4)](https://github.com/hailwood "hailwood (33 commits)")[![Jim-Webfox](https://avatars.githubusercontent.com/u/99769087?v=4)](https://github.com/Jim-Webfox "Jim-Webfox (29 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (16 commits)")[![reafeichtinger](https://avatars.githubusercontent.com/u/80401865?v=4)](https://github.com/reafeichtinger "reafeichtinger (11 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (11 commits)")[![Guesswhoitis](https://avatars.githubusercontent.com/u/63756285?v=4)](https://github.com/Guesswhoitis "Guesswhoitis (4 commits)")[![Ezekiel-Webfox](https://avatars.githubusercontent.com/u/114041728?v=4)](https://github.com/Ezekiel-Webfox "Ezekiel-Webfox (3 commits)")[![csoutham](https://avatars.githubusercontent.com/u/576413?v=4)](https://github.com/csoutham "csoutham (2 commits)")[![SuryaWebfox](https://avatars.githubusercontent.com/u/53416793?v=4)](https://github.com/SuryaWebfox "SuryaWebfox (2 commits)")[![vikas020807](https://avatars.githubusercontent.com/u/94953593?v=4)](https://github.com/vikas020807 "vikas020807 (1 commits)")[![adelf](https://avatars.githubusercontent.com/u/2818394?v=4)](https://github.com/adelf "adelf (1 commits)")

---

Tags

laravelwebfoxlaravel-backed-enumsreareafeichtingerlaravel-enums-plus

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/reafeichtinger-laravel-enums-plus/health.svg)

```
[![Health](https://phpackages.com/badges/reafeichtinger-laravel-enums-plus/health.svg)](https://phpackages.com/packages/reafeichtinger-laravel-enums-plus)
```

###  Alternatives

[spatie/laravel-data

Create unified resources and data transfer objects

1.7k28.9M627](/packages/spatie-laravel-data)[hirethunk/verbs

An event sourcing package that feels nice.

513162.9k6](/packages/hirethunk-verbs)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

123544.7k](/packages/worksome-exchange)[ralphjsmit/livewire-urls

Get the previous and current url in Livewire.

82270.3k4](/packages/ralphjsmit-livewire-urls)[hydrat/filament-table-layout-toggle

Filament plugin adding a toggle button to tables, allowing user to switch between Grid and Table layouts.

6292.3k1](/packages/hydrat-filament-table-layout-toggle)[ralphjsmit/laravel-helpers

A package containing handy helpers for your Laravel-application.

13704.6k2](/packages/ralphjsmit-laravel-helpers)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
