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

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

spatie/laravel-enum
===================

Laravel Enum support

3.3.0(2mo ago)3655.4M↓10.9%3620MITPHPPHP ^8.2CI passing

Since May 17Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/spatie/laravel-enum)[ Packagist](https://packagist.org/packages/spatie/laravel-enum)[ Docs](https://github.com/spatie/laravel-enum)[ Fund](https://spatie.be/open-source/support-us)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-laravel-enum/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (22)Versions (33)Used By (20)

Laravel support for spatie/enum
===============================

[](#laravel-support-for-spatieenum)

[![Latest Version on Packagist](https://camo.githubusercontent.com/438b7f86022f8b0074f5ea12ced93bca3bf66c0fcf7cafece976ca7adeb743ff/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d656e756d2e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/spatie/laravel-enum)[![License](https://camo.githubusercontent.com/9aa5d90daa900efa2d3a17bd7b26645550ab8ccfd146c9f02369e8fd9d1c7400/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7370617469652f6c61726176656c2d656e756d3f7374796c653d666f722d7468652d6261646765)](https://github.com/spatie/laravel-enum/blob/master/LICENSE.md)[![Postcardware](https://camo.githubusercontent.com/97c40bd733ff9974edecedb00f50f1815339c1fbdaedfdc8930069791979c9ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f737463617264776172652d2546302539462539322538432d3139373539333f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/97c40bd733ff9974edecedb00f50f1815339c1fbdaedfdc8930069791979c9ea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f506f737463617264776172652d2546302539462539322538432d3139373539333f7374796c653d666f722d7468652d6261646765)

[![Build Status](https://camo.githubusercontent.com/a5439439b67a23b3a5a0627ebe156507f83343d3fa6eb138d2e7cc966476bf5f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f7370617469652f6c61726176656c2d656e756d2f72756e2d74657374733f6c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/spatie/laravel-enum/actions?query=workflow%3Arun-tests)[![Total Downloads](https://camo.githubusercontent.com/2e551502dd3a3d83b9172b141a75fb46c9c01086afd19480f62a306c1344775d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-enum)

This package provides extended support for our [spatie/enum](https://github.com/spatie/enum) package in Laravel.

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

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-enum
```

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/a695e20ce58c09367be2f9dcb75f0033d82c54a3a53e5e551033c998d51e6ffd/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f6c61726176656c2d656e756d2e6a70673f743d31)](https://spatie.be/github-ad-click/laravel-enum)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Usage
-----

[](#usage)

```
// a Laravel specific base class
use Spatie\Enum\Laravel\Enum;

/**
 * @method static self DRAFT()
 * @method static self PREVIEW()
 * @method static self PUBLISHED()
 * @method static self ARCHIVED()
 */
final class StatusEnum extends Enum {}
```

### Model Attribute casting

[](#model-attribute-casting)

Chances are that if you're working in a Laravel project, you'll want to use enums within your models. This package provides two custom casts and the `\Spatie\Enum\Laravel\Enum` also implements the `\Illuminate\Contracts\Database\Eloquent\Castable` interface.

```
use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
    protected $casts = [
        'status' => StatusEnum::class,
        'nullable_enum' => StatusEnum::class.':nullable',
        'array_of_enums' => StatusEnum::class.':collection',
        'nullable_array_of_enums' => StatusEnum::class.':collection,nullable',
    ];
}
```

By using the casts the casted attribute will always be an instance of the given enum.

```
$model = new TestModel();
$model->status = StatusEnum::DRAFT();
$model->status->equals(StatusEnum::DRAFT());
```

### Validation Rule

[](#validation-rule)

This package provides a validation rule to validate your request data against a given enumerable.

```
use Spatie\Enum\Laravel\Rules\EnumRule;

$rules = [
    'status' => new EnumRule(StatusEnum::class),
];
```

This rule validates that the value of `status` is any possible representation of the `StatusEnum`.

But you can also use the simple string validation rule definition:

```
$rules = [
    'status' => [
        'enum:'.StatusEnum::class,
    ],
];
```

If you want to customize the failed validation messages you can publish the translation file.

```
php artisan vendor:publish --provider="Spatie\Enum\Laravel\EnumServiceProvider" --tag="translation"
```

We pass several replacements to the translation key which you can use.

- `attribute` - the name of the validated attribute
- `value` - the actual value that's validated
- `enum` - the full class name of the wanted enumerable
- `other` - a comma separated list of all possible values - they are translated via the `enums` array in the translation file

### Request Data Transformation

[](#request-data-transformation)

A common scenario is that you receive an enumerable value as part of your request data. To let you work with it as a real enum object you can transform request data to an enum in a similar way to the model attribute casting.

#### Request macro

[](#request-macro)

There is a request macro available which is the base for the other possible ways to cast request data to an enumerable.

```
$request->transformEnums($enumCastRules);
```

This is an example definition of all possible request enum castings. There are three predefined keys available as constants on `Spatie\Enum\Laravel\Http\EnumRequest` to cast enums only in specific request data sets. All other keys will be treated as independent enum casts and are applied to the combined request data set.

```
use Spatie\Enum\Laravel\Http\EnumRequest;

$enums = [
    // cast the status key independent of it's data set
    'status' => StatusEnum::class,
    // cast the status only in the request query params
    EnumRequest::REQUEST_QUERY => [
        'status' => StatusEnum::class,
    ],
    // cast the status only in the request post data
    EnumRequest::REQUEST_REQUEST => [
        'status' => StatusEnum::class,
    ],
    // cast the status only in the request route params
    EnumRequest::REQUEST_ROUTE => [
        'status' => StatusEnum::class,
    ],
];
```

You can call this macro yourself in every part of your code with access to a request instance. Most commonly you will do this in your controller action if you don't want to use one of the other two ways.

#### Form Requests

[](#form-requests)

Form requests are the easiest way to cast the data to an enum.

```
use Illuminate\Foundation\Http\FormRequest;
use Spatie\Enum\Laravel\Http\Requests\TransformsEnums;
use Spatie\Enum\Laravel\Rules\EnumRule;

class StatusFormRequest extends FormRequest
{
    use TransformsEnums;

    public function rules(): array
    {
        return [
            'status' => new EnumRule(StatusEnum::class),
            'properties.level' => new EnumRule(LevelEnum::class),
        ];
    }

    public function enums(): array
    {
        return [
            'status' => StatusEnum::class,
            'properties.level' => LevelEnum::class,
        ];
    }
}
```

The request data transformation is done after validation via the `FormRequest::passedValidation()` method. If you define your own `passedValidation()` method you have to call the request macro `transformEnums()` yourself.

```
protected function passedValidation()
{
    $this->transformEnums($this->enums());

    // ...
}
```

### Route Binding

[](#route-binding)

Beside using form requests, you can also use route binding. Similar [Laravel's Route Model Binding](https://laravel.com/docs/routing#route-model-binding), it automatically inject enum instances into your route action.

#### Implicit Binding

[](#implicit-binding)

To use implicit route binding, be sure add `Spatie\Enum\Laravel\Http\Middleware\SubstituteBindings` middleware. For example, add it in your `app\Http\Kernel.php`:

```
protected $middlewareGroups = [
    'web' => [
        // ...
        \Spatie\Enum\Laravel\Http\Middleware\SubstituteEnumBindings::class,
    ],
];
```

Use a type-hinted variable name that matches route segment to use implicit route binding.

```
Route::get('/posts/{status}', function (StatusEnum $status) {
    return $status;
});
```

#### Explicit Binding

[](#explicit-binding)

To have an explicit binding, there is a `Route::enum()` macro. It's important that your route/group uses the `\Illuminate\Routing\Middleware\SubstituteBindings` middleware. This middleware is enabled by default for the `web` route group.

```
Route::enum('status', StatusEnum::class);
Route::get('/posts/{status}', function (Request $request) {
    return $request->route('status');
});
```

### Enum Make Command

[](#enum-make-command)

We provide an artisan make command which allows you to quickly create new enumerables.

```
php artisan make:spatie-enum StatusEnum
```

You can use `--method` option to predefine some enum values - you can use them several times.

### Faker Provider

[](#faker-provider)

It's very likely that you will have a model with an enum attribute and you want to generate random enum values in your model factory. Because doing so with default [faker](https://github.com/fzaninotto/Faker) is a lot of copy'n'paste we've got you covered with a faker provider `Spatie\Enum\Laravel\Faker\FakerEnumProvider`. The static `register()` method is only a little helper - you can for sure register the provider the default way `$faker->addProvider(new FakerEnumProvider)`.

The faker methods itself are inherited from the base packages [Faker Provider](https://github.com/spatie/enum#faker-provider).

### Livewire

[](#livewire)

You can use an enum as a property on a Livewire component like this:

```
class ShowCustomer extends Component
{
    public StatusEnum $statusEnum;

    public function mount($id)
    {
        $customer = Customer::find($id);
        $this->statusEnum = $customer->status;
    }

    public function render()
    {
        return view('livewire.customer');
    }
}
```

Just one thing is required to make this work: implement `\Livewire\Wireable` on all the enums you’ll be using with Livewire::

```
use Livewire\Wireable;

/**
 * @method static self pending()
 * @method static self active()
 */
final class StatusEnum implements Wireable
{}
```

Testing
-------

[](#testing)

```
composer test
composer test-coverage
```

Changelog
---------

[](#changelog)

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

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

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

### Security

[](#security)

If you've found a bug regarding security please mail  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Brent Roose](https://github.com/brendt)
- [Tom Witkowski](https://github.com/Gummibeer)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

72

—

ExcellentBetter than 100% of packages

Maintenance88

Actively maintained with recent releases

Popularity63

Solid adoption and visibility

Community39

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 64.4% 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 ~86 days

Recently: every ~283 days

Total

30

Last Release

61d ago

Major Versions

1.6.1 → 2.0.0-rc.22020-09-09

2.5.2 → 3.0.02022-02-04

PHP version history (5 changes)1.0.0-beta.1PHP ^7.2

2.0.0-rc.2PHP ^7.4

2.1.0PHP ^7.4 || ^8.0

3.1.0PHP ^8.0

3.3.0PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![Gummibeer](https://avatars.githubusercontent.com/u/6187884?v=4)](https://github.com/Gummibeer "Gummibeer (270 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (41 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (30 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (11 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (10 commits)")[![justinaskav](https://avatars.githubusercontent.com/u/23059846?v=4)](https://github.com/justinaskav "justinaskav (9 commits)")[![dpetrovaliev](https://avatars.githubusercontent.com/u/53557596?v=4)](https://github.com/dpetrovaliev "dpetrovaliev (7 commits)")[![gaelreyrol](https://avatars.githubusercontent.com/u/498465?v=4)](https://github.com/gaelreyrol "gaelreyrol (7 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (6 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (5 commits)")[![andrewminion-luminfire](https://avatars.githubusercontent.com/u/47227887?v=4)](https://github.com/andrewminion-luminfire "andrewminion-luminfire (3 commits)")[![supertassu](https://avatars.githubusercontent.com/u/9721638?v=4)](https://github.com/supertassu "supertassu (3 commits)")[![xewl](https://avatars.githubusercontent.com/u/245041?v=4)](https://github.com/xewl "xewl (2 commits)")[![telkins](https://avatars.githubusercontent.com/u/53731?v=4)](https://github.com/telkins "telkins (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![Skullbock](https://avatars.githubusercontent.com/u/1104083?v=4)](https://github.com/Skullbock "Skullbock (1 commits)")[![thecaliskan](https://avatars.githubusercontent.com/u/13554944?v=4)](https://github.com/thecaliskan "thecaliskan (1 commits)")[![nicolasbeauvais](https://avatars.githubusercontent.com/u/2951704?v=4)](https://github.com/nicolasbeauvais "nicolasbeauvais (1 commits)")[![craigpotter](https://avatars.githubusercontent.com/u/1442635?v=4)](https://github.com/craigpotter "craigpotter (1 commits)")[![charlietennant](https://avatars.githubusercontent.com/u/46321647?v=4)](https://github.com/charlietennant "charlietennant (1 commits)")

---

Tags

enumlaravelphpspatielaravelenumlaravel-enum

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spatie-laravel-enum/health.svg)

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

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[aedart/athenaeum

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

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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