PHPackages                             mindtwo/native-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. mindtwo/native-enum

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

mindtwo/native-enum
===================

Package for using native php enums.

1.10(1y ago)2626.0k↓19.1%11MITPHPPHP &gt;=8.2

Since Mar 14Pushed 1mo ago6 watchersCompare

[ Source](https://github.com/mindtwo/native-enum)[ Packagist](https://packagist.org/packages/mindtwo/native-enum)[ Docs](https://github.com/mindtwo/native-enum)[ RSS](/packages/mindtwo-native-enum/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (7)Versions (20)Used By (1)

Laravel Native PHP 8.1 Enums
============================

[](#laravel-native-php-81-enums)

[![Latest Version on Packagist](https://camo.githubusercontent.com/da79501c1d7c8ae0878f0da0bda74368a59994bb3aab543001b98717ea61ae22/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d696e6474776f2f6e61746976652d656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mindtwo/native-enum)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/565b15bff3b202865703bc8c2b1211a729ddb3604eb9a0f75d87c92e8d47c701/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6d696e6474776f2f6e61746976652d656e756d2f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://app.travis-ci.com/github/mindtwo/native-enum)[![Total Downloads](https://camo.githubusercontent.com/66ee8d730f8a6d791ebbe2a13e35aa71a013e0a47d4d6fcc458f3abaa4211373/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d696e6474776f2f6e61746976652d656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mindtwo/native-enum)

[![mindtwo GmbH](https://github.com/mindtwo/native-enum/raw/master/assets/header.png?raw=true)](https://www.mindtwo.de/digitalagentur)

Enums are an invaluable tool for any developer working with PHP. They provide a way to easily and efficiently define a set of constants that can be used throughout a project. Enums also help to make code more maintainable and scalable. For example, they can help to define a set of values that must stay consistent throughout the project, like a list of permissions or statuses. This helps ensure that the same values are used in all the relevant parts of the code and that any changes are made in one place. Additionally, enums help to reduce the amount of manual testing needed since the values are already defined. Furthermore, enums provide a way for developers to quickly check for valid values, making it easier to spot errors in code and ensure that the application behaves as expected. Finally, enums are strongly typed, meaning that they can help to ensure that the correct type of data is used in each part of the application, which can help to improve overall code quality.

Inspired by the package [BenSampo/laravel-enum](https://github.com/BenSampo/laravel-enum) this one uses the new native enums classes in PHP. The native functions are extended to work easily ams seamlessly with them in Laravel-based systems.

Everyone is welcome to contribute.

Enojy the Package!

Overview
--------

[](#overview)

- [Install](Install)
    - [Requirements](#requirements)
    - [Composer install](#composer-install)
- [Create enum](#create-enum)
    - [Artisan command](#artisan-command)
    - [Manual enum creation](#manual-enum-creation)
- [Usage](#usage)
    - [Base usage](#base-usage)
    - [Get specific enum values](#get-specific-enum-values)
    - [Get specific enum names](#get-specific-enum-names)
    - [Use static calls to get the primitive value](#use-static-calls-to-get-the-primitive-value)
    - [Validation](#validation)
    - [Localized enum](#localized-enum)

Install
-------

[](#install)

Installing the PHP Composer Package
-----------------------------------

[](#installing-the-php-composer-package)

Laravel Native PHP 8.1 Enums is a powerful package that can help you construct and maintain robust and scalable Laravel-based systems.

### Requirements

[](#requirements)

- Laravel 9 or higher
- PHP 8.1 or higher

### Composer install

[](#composer-install)

Before you begin, you'll need to make sure you have the listed requirements and Composer installed on your system. You can find instructions for doing so [here](https://getcomposer.org/doc/00-intro.md).

Once you have Composer installed, you can install "Laravel Native PHP 8.1 Enums" by running the following command from your project directory:

```
composer require mindtwo/native-enum
```

After the installation is complete, you'll now be ready to start using native enums in your project. Have fun!

Create enum
-----------

[](#create-enum)

### Artisan command

[](#artisan-command)

You can use the following Artisan command to generate a new native enum class in your project:

```
// Default:
php artisan make:enum UserRole

// Localized:
php artisan make:enum UserRole --localized
```

### Manual enum creation

[](#manual-enum-creation)

You can also create a new native enum manually. The structure should look like this:

```
namespace App\Enums;

enum UserRole: int
{
    use BaseEnum;

    case ADMIN = 10;
    case CUSTOMER = 50;
}
```

Usage
-----

[](#usage)

### Base usage

[](#base-usage)

```
UserRole::getRandomValue();
UserRole::getRandomName();
UserRole::getRandomInstance();
UserRole::asSelectArray();
UserRole::asArray();
UserRole::getValues();
UserRole::getNames();
UserRole::hasValue(50);
UserRole::hasName('ADMIN');
```

### Get specific enum values

[](#get-specific-enum-values)

```
UserRole::getValues('ADMIN');
UserRole::getValues(UserRole::ADMIN);
UserRole::getValues([UserRole::ADMIN]);
UserRole::getValues('CUSTOMER');
UserRole::getValues(UserRole::CUSTOMER);
UserRole::getValues([UserRole::CUSTOMER]);
```

### Get specific enum names

[](#get-specific-enum-names)

```
UserRole::getNames(10);
UserRole::getNames(50);
UserRole::getNames([10,50]);
```

### Use static calls to get the primitive value

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

```
UserRole::ADMIN(); // 10
UserRole::CUSTOMER(); // 50
```

### Validation

[](#validation)

#### Enum value

[](#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.

```
use mindtwo\NativeEnum\Rules\EnumValue;

public function store(Request $request)
{
    $this->validate($request, [
        'user_role' => ['required', new EnumValue(UserRole::class)],
    ]);
}
```

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.

```
new EnumValue(UserRole::class, false) // Turn off strict type checking.
```

#### Enum name

[](#enum-name)

You can also validate on names using the `EnumName` rule. This is useful if you're taking the enum name as a URL parameter for sorting or filtering for example.

```
use mindtwo\NativeEnum\Rules\EnumKey;

public function store(Request $request)
{
    $this->validate($request, [
        'user_role' => ['required', new EnumName(UserRole::class)],
    ]);
}
```

#### Enum instance

[](#enum-instance)

Additionally you can validate that a parameter is an instance of a given enum.

```
use mindtwo\NativeEnum\Rules\Enum;

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

### Localized enum

[](#localized-enum)

The Enum has to implement the `LocalizedEnum` interface:

```
namespace App\Enums;

enum UserRole: int implements LocalizedEnum
{
    use BaseEnum;

    case ADMIN = 10;
    case CUSTOMER = 50;
}
```

Translation files can be placed here `lang/en/enums.php` like:

```
use \App\Enums;

return [

    Enums\UserRole::class => [
        Enums\UserRole::ADMIN->name => 'Administrator',
        Enums\UserRole::CUSTOMER->name => 'Customer',
    ],

];
```

To get a translated name of a selected enum value:

```
Enums\UserRole::ADMIN->name(); // Returns "Administrator"
```

### Casts in Eloquent Models

[](#casts-in-eloquent-models)

Laravel's Eloquent ORM provides a powerful and expressive way to handle data in your database. When working with custom data types, like enums, it's often useful to define how these values should be cast when interacting with the database. This is where casting comes into play.

#### Using EnumCast in Models

[](#using-enumcast-in-models)

If you want to use an enum in your Eloquent model, you can leverage the `EnumCast` feature to ensure that the enum values are correctly transformed when reading from or writing to the database. This is particularly useful when dealing with attributes that have a specific set of allowed values, such as user roles, statuses, or types.

Here’s how you can apply `EnumCast` in your model:

```
namespace App\Models;

use App\Enums\UserRole;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'role' => UserRole::class,
    ];
}
```

In the example above, the `role` attribute of the `User` model is cast to the `UserRole` enum. This means that whenever you access the `role` attribute, Eloquent will automatically convert the raw database value into an instance of `UserRole`. Similarly, when you assign a `UserRole` enum instance to the `role` attribute, Eloquent will handle the conversion to its underlying value when saving it to the database.

#### Handling Nullable Values

[](#handling-nullable-values)

In some cases, an attribute might be optional and could have a `null` value in the database. If you need to support `null` values for an enum cast, you can do so by appending `:nullable` to the cast definition:

1. Define the cast with the `:nullable` modifier:

```
protected $casts = [
    'role' => UserRole::class . ':nullable',
];
```

2. Ensure that the enum class implements the `Illuminate\Contracts\Database\Eloquent\Castable` contract.

```
namespace App\Enums;

use Illuminate\Contracts\Database\Eloquent\Castable;

enum UserRole: int implements Castable
{
    use BaseEnum;

    case ADMIN = 10;
    case CUSTOMER = 50;
}
```

IMPORTANT: The `Illuminate\Contracts\Database\Eloquent\Castable` contract is required to support nullable enum values in Eloquent models. Make sure that your enum class implements this contract to avoid errors when using the `:nullable` modifier.

With this setup, the `role` attribute can be `null`, and Eloquent will correctly handle it without throwing errors. This is useful for scenarios where an enum value may not be set initially or where it can be removed at a later time.

#### Casting Collections of Enums

[](#casting-collections-of-enums)

Sometimes, you may have a model attribute that stores an array or collection of enum values. For instance, a user might have multiple roles, and these roles are stored as an array in the database. You can cast these arrays to collections of enum instances by using the `:collection` modifier:

1. Define the cast with the `:collection` modifier:

```
protected $casts = [
    'roles' => UserRole::class . ':collection',
];
```

2. Ensure that the enum class implements the `Illuminate\Contracts\Database\Eloquent\Castable` contract.

```
namespace App\Enums;

use Illuminate\Contracts\Database\Eloquent\Castable;

enum UserRole: int implements Castable
{
    use BaseEnum;

    case ADMIN = 10;
    case CUSTOMER = 50;
}
```

IMPORTANT: The `Illuminate\Contracts\Database\Eloquent\Castable` contract is required to support casting collections of enum values in Eloquent models. Make sure that your enum class implements this contract to avoid errors when using the `:collection` modifier.

With this configuration, the `roles` attribute will be cast to a collection of `UserRole` enum instances. When you retrieve this attribute, Eloquent will return a collection where each item is an instance of `UserRole`. Similarly, when you assign a collection or array of `UserRole` instances to the `roles` attribute, Eloquent will properly convert and store the underlying values in the database.

Change log
----------

[](#change-log)

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

Testing
-------

[](#testing)

```
$ composer test
```

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [All Devs @ mindtwo](https://www.mindtwo.de/digitalagentur)
- [BenSampo/laravel-enum](https://github.com/BenSampo/laravel-enum)
- [archtechx/enums](https://github.com/archtechx/enums)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

[![Back to the top](https://camo.githubusercontent.com/95bc64effcf1548b818d9d08d6b7586b242de6e42c5756a357f897afb9f635e2/68747470733a2f2f7777772e6d696e6474776f2e64652f646f776e6c6f6164732f646f6f646c65732f6769746875622f7265706f7369746f72792d666f6f7465722e706e67)](#)

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance69

Regular maintenance activity

Popularity37

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 80.5% of commits — single point of failure

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 ~63 days

Recently: every ~50 days

Total

18

Last Release

447d ago

PHP version history (2 changes)1.5PHP &gt;=8.1

1.8.5PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/4cc86fe6179314d204b14d1c81eb09a87ef84b0bcf2360dcd981171d1346c077?d=identicon)[mindtwo](/maintainers/mindtwo)

---

Top Contributors

[![jonasemde](https://avatars.githubusercontent.com/u/5083193?v=4)](https://github.com/jonasemde "jonasemde (33 commits)")[![blumewas](https://avatars.githubusercontent.com/u/5960093?v=4)](https://github.com/blumewas "blumewas (6 commits)")[![ankurk91](https://avatars.githubusercontent.com/u/6111524?v=4)](https://github.com/ankurk91 "ankurk91 (1 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (1 commits)")

---

Tags

phplaravelenumilluminatelaravel-enumphp 8.1native-enum

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mindtwo-native-enum/health.svg)

```
[![Health](https://phpackages.com/badges/mindtwo-native-enum/health.svg)](https://phpackages.com/packages/mindtwo-native-enum)
```

###  Alternatives

[spatie/laravel-enum

Laravel Enum support

3655.4M31](/packages/spatie-laravel-enum)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[monicahq/laravel-cloudflare

Add Cloudflare ip addresses to trusted proxies for Laravel.

3372.7M4](/packages/monicahq-laravel-cloudflare)[laragear/preload

Effortlessly make a Preload script for your Laravel application.

119363.5k](/packages/laragear-preload)[napp/xray-laravel

AWS X-Ray for Laravel applications.

61407.3k](/packages/napp-xray-laravel)[lazerg/laravel-enum-pro

A powerful PHP enum extension with collection support, random selection, and magic static calls

4319.0k](/packages/lazerg-laravel-enum-pro)

PHPackages © 2026

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