PHPackages                             biiiiiigmonster/laravel-enum - 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. biiiiiigmonster/laravel-enum

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

biiiiiigmonster/laravel-enum
============================

laravel enum helper base php version 8.1

v1.4.0(1y ago)20197↓63.6%2[4 PRs](https://github.com/biiiiiigmonster/laravel-enum/pulls)MITPHPCI passing

Since Jun 20Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/biiiiiigmonster/laravel-enum)[ Packagist](https://packagist.org/packages/biiiiiigmonster/laravel-enum)[ Docs](https://github.com/biiiiiigmonster/laravel-enum)[ RSS](/packages/biiiiiigmonster-laravel-enum/feed)WikiDiscussions laravel-v10 Synced 3w ago

READMEChangelog (10)Dependencies (10)Versions (21)Used By (0)

laravel enum helper base php version 8.1
========================================

[](#laravel-enum-helper-base-php-version-81)

[![Latest Version on Packagist](https://camo.githubusercontent.com/46bdb25456103350e612efd2d9b9db273c94b8b168350db53a5a3b5bd79854d1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f62696969696969676d6f6e737465722f6c61726176656c2d656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/biiiiiigmonster/laravel-enum)[![GitHub Tests Action Status](https://camo.githubusercontent.com/5d8b979b133578d9b31fb5d092a24c95323ab0ada1da1b62d1a2e280fe93ae52/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f62696969696969676d6f6e737465722f6c61726176656c2d656e756d2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/biiiiiigmonster/laravel-enum/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/c0aaf335b3caa3ee0cba57d9903621c6a90e88b537d2227a8db9112398b608f6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f62696969696969676d6f6e737465722f6c61726176656c2d656e756d2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/biiiiiigmonster/laravel-enum/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Coverage Status](https://camo.githubusercontent.com/8f166e377106d90e63873813d070cdd1421a4781a41e2961928b7c28f3f72130/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f62696969696969676d6f6e737465722f6c61726176656c2d656e756d2f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/biiiiiigmonster/laravel-enum?branch=main)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/58a96256b822ed280dd90d68e3411ff311287eef606e062610db2f5a28778ac8/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f62696969696969676d6f6e737465722f6c61726176656c2d656e756d2e7376673f6c6162656c3d5363727574696e697a6572267374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/biiiiiigmonster/laravel-enum/)[![Total Downloads](https://camo.githubusercontent.com/4039d0af50d1d3c535a18a6e3541ab4df72234286391767f781f5e068c07dc71/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f62696969696969676d6f6e737465722f6c61726176656c2d656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/biiiiiigmonster/laravel-enum)

Enum helper for laravel10 based on the enum feature of php 8.1.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require biiiiiigmonster/laravel-enum
```

Usage
-----

[](#usage)

To get started, enums typically live in the `app\Enums` directory. You may use the `make:enum` Artisan command to generate a new enum:

```
php artisan make:enum TaskStatus
```

if you want to generate a [backed](https://www.php.net/manual/en/language.enumerations.backed.php) enum, you may use the `make:enum` Artisan command with `--type` options:

```
php artisan make:enum TaskStatus --type=int
```

and also you can apply the trait on your exists enum:

```
use BiiiiiigMonster\LaravelEnum\Concerns\EnumTraits;

// pure enum.
enum Role
{
    use EnumTraits;

    case ADMINISTRATOR;
    case SUBSCRIBER;
    case GUEST;
}

// backed enum.
enum TaskStatus: int
{
    use EnumTraits;

    case INCOMPLETE = 0;
    case COMPLETED = 1;
    case CANCELED = 2;
}
```

### Invokable

[](#invokable)

This helper lets you get the primitive value of a backed enum, or the name of a pure enum, by "invoking" it — either statically (`MyEnum::FOO()` instead of `MyEnum::FOO`), or as an instance (`$enum()`).

That way, you can use enums as array keys:

```
'statuses' => [
    TaskStatus::INCOMPLETE() => ['some configuration'],
    TaskStatus::COMPLETED() => ['other configuration'],
],
```

Or access the underlying primitives for any other use cases:

```
public function updateStatus(int $status): void;

$task->updateStatus(TaskStatus::COMPLETED());
```

The main point: this is all without having to append `->value` to everything:

```
TaskStatus::CANCELED; // => TaskStatus instance
TaskStatus::CANCELED(); // => 2
```

#### Use static calls to get the primitive value

[](#use-static-calls-to-get-the-primitive-value)

```
TaskStatus::INCOMPLETE(); // 0
TaskStatus::COMPLETED(); // 1
TaskStatus::CANCELED(); // 2
Role::ADMINISTRATOR(); // 'ADMINISTRATOR'
Role::SUBSCRIBER(); // 'SUBSCRIBER'
Role::GUEST(); // 'GUEST'
```

#### Invoke instances to get the primitive value

[](#invoke-instances-to-get-the-primitive-value)

```
public function updateStatus(TaskStatus $status, Role $role)
{
    $this->record->setStatus($status(), $role());
}
```

### Enhancement

[](#enhancement)

Helper provide many static methods for you to enhance experience with enums.

#### Names

[](#names)

This helper returns a list of case *names* in the enum.

```
TaskStatus::names(); // ['INCOMPLETE', 'COMPLETED', 'CANCELED']
Role::names(); // ['ADMINISTRATOR', 'SUBSCRIBER', 'GUEST']
```

#### Values

[](#values)

This helper returns a list of case *values* for backed enums, or a list of case *names* for pure enums (making this functionally equivalent to [`::names()`](#names) for pure Enums)

```
TaskStatus::values(); // [0, 1, 2]
Role::values(); // ['ADMINISTRATOR', 'SUBSCRIBER', 'GUEST']
```

#### Options

[](#options)

This helper returns an array, that key is each instance invoke `()` return, and value is instance [`->label()`](#labels) returns.

```
TaskStatus::options();
/*
    [
        0 => 'Incomplete',
        1 => 'Completed',
        2 => 'Canceled'
    ]
*/
Role::options();
/*
    [
        'ADMINISTRATOR' => 'Administrator',
        'SUBSCRIBER' => 'Subscriber',
        'GUEST' => 'Guest'
    ]
*/
```

#### Tables

[](#tables)

This helper returns a list of case map array that each instance, if instance append attributes that extended [`Meta`](#meta), the map array including more.

```
TaskStatus::tables();
/*
    [
        ['name' => 'INCOMPLETE', 'value' => 0],
        ['name' => 'COMPLETED', 'value' => 1],
        ['name' => 'CANCELED', 'value' => 2]
    ]
*/
Role::tables();
/*
    [
        ['name' => 'ADMINISTRATOR'],
        ['name' => 'SUBSCRIBER'],
        ['name' => 'GUEST']
    ]
*/
```

#### From

[](#from)

This helper adds `from()` and `tryFrom()` to pure enums, and adds `fromName()` and `tryFromName()` to all enums.

**Important Notes**:

- `BackedEnum` instances already implement their own `from()` and `tryFrom()` methods, which will not be overridden by this trait. Attempting to override those methods in a `BackedEnum` causes a fatal error.
- Pure enums only have named cases and not values, so the `from()` and `tryFrom()` methods are functionally equivalent to `fromName()` and `tryFromName()`

##### Use the `from()` method

[](#use-the-from-method)

```
Role::from('ADMINISTRATOR'); // Role::ADMINISTRATOR
Role::from('NOBODY'); // Error: ValueError
```

##### Use the `tryFrom()` method

[](#use-the-tryfrom-method)

```
Role::tryFrom('GUEST'); // Role::GUEST
Role::tryFrom('NEVER'); // null
```

##### Use the `fromName()` method

[](#use-the-fromname-method)

```
TaskStatus::fromName('INCOMPLETE'); // TaskStatus::INCOMPLETE
TaskStatus::fromName('MISSING'); // Error: ValueError
Role::fromName('SUBSCRIBER'); // Role::SUBSCRIBER
Role::fromName('HACKER'); // Error: ValueError
```

##### Use the `tryFromName()` method

[](#use-the-tryfromname-method)

```
TaskStatus::tryFromName('COMPLETED'); // TaskStatus::COMPLETED
TaskStatus::tryFromName('NOTHING'); // null
Role::tryFromName('GUEST'); // Role::GUEST
Role::tryFromName('TESTER'); // null
```

#### Random

[](#random)

This helper returns an instance of case by random.

```
TaskStatus::random(); // TaskStatus::COMPLETED
Role::random(); // Role::GUEST
```

#### Default Case

[](#default-case)

Sometimes you may need to specify default case for your enum, which is easy as below: simply append the `#[DefaultCase]` attribute to the case:

```
use BiiiiiigMonster\LaravelEnum\Attributes\DefaultCase;
use BiiiiiigMonster\LaravelEnum\Concerns\EnumTraits;

enum Role
{
    use EnumTraits;

    #[DefaultCase]
    case ADMIN;

    case GUEST;
}
```

Then use the `::default()` static method to get this case instance:

```
Role::default(); // Role::ADMIN

Role::ADMIN->isDefault(); // true
```

### Meta

[](#meta)

This feature lets you add metadata to enum cases, it's used by way of attributes.

```
use BiiiiiigMonster\LaravelEnum\Concerns\EnumTraits;
use App\Enums\Metas\{Description, Color};

enum TaskStatus: int
{
    use EnumTraits;

    #[Description('Incomplete Task')] #[Color('red')]
    case INCOMPLETE = 0;

    #[Description('Completed Task')] #[Color('green')]
    case COMPLETED = 1;

    #[Description('Canceled Task')] #[Color('gray')]
    case CANCELED = 2;
}
```

#### Creating meta attributes

[](#creating-meta-attributes)

To generate a new meta attributes, you may use the `make:enumMeta` Artisan command:

```
php artisan make:enumMeta Color
```

meta attribute needs to exist as an Attribute.

```
use BiiiiiigMonster\LaravelEnum\Concerns\Meta;
use Attribute;

#[Attribute]
class Color extends Meta {}

#[Attribute]
class Description extends Meta {}
```

Inside the attribute, you can customize a few things. For instance, you may want to use a different method name than the one derived from the class name (`Description` becomes `description()` by default). To do that, define the `alias` static property on the meta:

```
#[Attribute]
class Description extends Meta
{
    public static string $alias = 'note';
}
```

With the code above, the `->description()` of a case will be accessible as `->note()`.

Another thing you can customize is the passed value. For instance, to wrap a color name like `text-{$color}-500`, you'd add the following `transform()` method:

```
#[Attribute]
class Color extends Meta
{
    protected function transform(mixed $value): string
    {
        return "text-{$value}-500";
    }
}
```

And now the returned color will be correctly transformed:

```
TaskStatus::COMPLETED->color(); // 'text-green-500'
```

#### Access the metadata

[](#access-the-metadata)

By accessing the attribute method name, you can get the meta value:

```
TaskStatus::INCOMPLETE->description(); // 'Incomplete Task'
TaskStatus::COMPLETED->color(); // 'green'
```

Also, [`::tables()`](#tables) static method can return all meta attribute maps on each instance.

```
$tables = TaskStatus::tables();

// $tables
[
    [
        'name' => 'INCOMPLETE',
        'value' => 0,
        'description' => 'Incomplete Task',
        'color' => 'red'
    ],
    [
        'name' => 'COMPLETED',
        'value' => 1,
        'description' => 'Completed Task',
        'color' => 'green'
    ],
    [
        'name' => 'CANCELED',
        'value' => 2,
        'description' => 'Canceled Task',
        'color' => 'gray'
    ]
]
```

#### Use the `fromMeta()` method

[](#use-the-frommeta-method)

Similarly, you can also get the enum case instance through the meta instance.

```
$green = Color::make('green');// new Color('green');
$blue = Color::make('blue');// new Color('blue');

TaskStatus::fromMeta($green); // TaskStatus::COMPLETED
TaskStatus::fromMeta($blue); // Error: ValueError
```

#### Use the `tryFromMeta()` method

[](#use-the-tryfrommeta-method)

```
TaskStatus::tryFromMeta($green); // TaskStatus::COMPLETED
TaskStatus::tryFromMeta($blue); // null
```

Validation
----------

[](#validation)

Usually, we need limit your application's incoming data to a specified enums, laravel provides the basic rule, but here we have perfected it.

### Array Validation

[](#array-validation)

You can use the 'array' syntax for rules.

#### Enum

[](#enum)

Validate that a parameter is an instance of a given enum, it's similar to [`Enum Rules`](https://laravel.com/docs/10.x/validation#rule-enum) and can support pure enums.

```
use BiiiiiigMonster\LaravelEnum\Rules\Enum;

public function store(Request $request)
{
    $this->validate($request, [
        'status' => ['required', new Enum(TaskStatus::class)],
        'role' => ['required', new Enum(Role::class)],
    ]);
}
```

#### EnumMeta

[](#enummeta)

Additionally, validate that a parameter is an instance of the given meta in the given enum.

```
use BiiiiiigMonster\LaravelEnum\Rules\EnumMeta;

public function store(Request $request)
{
    $this->validate($request, [
        'color' => ['required', new EnumMeta(TaskStatus::class, Color::class)],
    ]);
}
```

`EnumMeta` rule takes two parameters, the first is given enum, the second is given meta, if parameter name is same of meta method name, you can omit it:

```
'color' => ['required', new EnumMeta(TaskStatus::class)],
```

### Pipe Validation

[](#pipe-validation)

You can also use the 'pipe' syntax for rules.

- **enumerate**: *enum\_class*
- **enum\_meta**: *enum\_class,\[meta\_attribute\]*

```
'status' => 'required|enumerate:' . TaskStatus::class,
'color' => 'required|enum_meta:' . TaskStatus::class . ',' . Color::class,
```

### Validation messages

[](#validation-messages)

If needed, you can modify the error message when validated fails.

Run the following command to publish the language files to your `lang` folder:

```
php artisan vendor:publish --provider="BiiiiiigMonster\LaravelEnum\EnumServiceProvider" --tag="translations"

```

Localization
------------

[](#localization)

### Labels

[](#labels)

The enum instances are descriptive, and we have added translation capabilities for this. You can translate the strings returned by the enum instance's `->label()` method using Laravel's built-in [localization](https://laravel.com/docs/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:

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