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

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

spatie/enum
===========

PHP Enums

3.13.0(4y ago)84529.1M—5.9%6720MITPHPPHP ^8.0CI passing

Since Feb 7Pushed 4w ago8 watchersCompare

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

READMEChangelog (10)Dependencies (4)Versions (49)Used By (20)

Enum
====

[](#enum)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d5490979258a2f469e1ce2f46607e8bfe4696b5fadcf1ce4cdeaadb19a3f82fe/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/enum)[![GitHub Tests Action Status](https://camo.githubusercontent.com/3970017f77294e6e17fdfecd09cafdb75973e8d5514e3b31ccde7166ab9704a0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f656e756d2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/spatie/enum/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/19e81f423839300e129530233f52efa396e053e1a700334d059e425b8c43fd9a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7370617469652f656e756d2f7068702d63732d66697865722e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/spatie/enum/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/a4c3185d5362523b0a2caae8eda81186eff4effe431b826ffe5e15ae4aeb033a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f656e756d2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/enum)

> ⚠️ With the introduction of **Enums** in PHP 8.1, this package is now considered obsolete. For new projects, we recommend using **native enums** instead of this package. Learn more about native enums here:

---

This package offers strongly typed enums in PHP. In this package, enums are always objects, never constant values on their own. This allows for proper static analysis and refactoring in IDEs.

Here's how enums are created with this package:

```
use \Spatie\Enum\Enum;

/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}
```

And this is how they are used:

```
public function setStatus(StatusEnum $status): void
{
    $this->status = $status;
}

// ...

$class->setStatus(StatusEnum::draft());
```

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

[](#support-us)

[![](https://camo.githubusercontent.com/970de81efd25ed92a4ee0e65c27ea9953effc77066d38bcdc4102216a3eb0452/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f656e756d2e6a70673f743d31)](https://spatie.be/github-ad-click/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).

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

[](#installation)

You can install the package via composer:

```
composer require spatie/enum
```

Usage
-----

[](#usage)

This is how an enum can be defined.

```
/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
}
```

This is how they are used:

```
public function setStatus(StatusEnum $status)
{
    $this->status = $status;
}

// ...

$class->setStatus(StatusEnum::draft());
```

AutocompletionRefactoring[![](./docs/autocomplete.gif)](./docs/autocomplete.gif)[![](./docs/refactor.gif)](./docs/refactor.gif)### Creating an enum from a value

[](#creating-an-enum-from-a-value)

```
$status = StatusEnum::from('draft');
```

When an enum value doesn't exist, you'll get a `BadMethodCallException`. If you would prefer not catching an exception, you can use:

```
$status = StatusEnum::tryFrom('draft');
```

When an enum value doesn't exist in this case, `$status` will be `null`.

The only time you want to construct an enum from a value is when unserializing them from eg. a database.

If you want to get the value of an enum to store it, you can do this:

```
$status->value;
```

Note that `value` is a read-only property, it cannot be changed.

### Enum values

[](#enum-values)

By default, the enum value is its method name. You can however override it, for example if you want to store enums as integers in a database, instead of using their method name.

```
/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
    protected static function values(): array
    {
        return [
            'draft' => 1,
            'published' => 2,
            'archived' => 3,
        ];
    }
}
```

An enum value doesn't have to be a `string`, as you can see in the example it can also be an `int`.

Note that you don't need to override all values. Rather, you only need to override the ones that you want to be different from the default.

If you have a logic that should be applied to all method names to get the value, like lowercase them, you can return a `Closure`.

```
/**
 * @method static self DRAFT()
 * @method static self PUBLISHED()
 * @method static self ARCHIVED()
 */
class StatusEnum extends Enum
{
    protected static function values(): Closure
    {
        return function(string $name): string|int {
            return mb_strtolower($name);
        };
    }
}
```

### Enum labels

[](#enum-labels)

Enums can be given a label, you can do this by overriding the `labels` method.

```
/**
 * @method static self draft()
 * @method static self published()
 * @method static self archived()
 */
class StatusEnum extends Enum
{
    protected static function labels(): array
    {
        return [
            'draft' => 'my draft label',
        ];
    }
}
```

Note that you don't need to override all labels, the default label will be the enum's value.

If you have a logic that should be applied to all method names to get the label, like lowercase them, you can return a `Closure` as in the value example.

You can access an enum's label like so:

```
$status->label;
```

Note that `label` is a read-only property, it cannot be changed.

### Comparing enums

[](#comparing-enums)

Enums can be compared using the `equals` method:

```
$status->equals(StatusEnum::draft());
```

You can pass several enums to the `equals` method, it will return `true` if the current enum equals one of the given values.

```
$status->equals(StatusEnum::draft(), StatusEnum::archived());
```

### Phpunit Assertions

[](#phpunit-assertions)

This package provides an abstract class `Spatie\Enum\Phpunit\EnumAssertions` with some basic/common assertions if you have to test enums.

```
use Spatie\Enum\Phpunit\EnumAssertions;

EnumAssertions::assertIsEnum($post->status); // checks if actual extends Enum::class
EnumAssertions::assertIsEnumValue(StatusEnum::class, 'draft'); // checks if actual is a value of given enum
EnumAssertions::assertIsEnumLabel(StatusEnum::class, 'draft'); // checks if actual is a label of given enum
EnumAssertions::assertEqualsEnum(StatusEnum::draft(), 'draft'); // checks if actual (transformed to enum) equals expected
EnumAssertions::assertSameEnum(StatusEnum::draft(), $post->status); // checks if actual is same as expected
EnumAssertions::assertSameEnumValue(StatusEnum::draft(), 1); // checks if actual is same value as expected
EnumAssertions::assertSameEnumLabel(StatusEnum::draft(), 'draft'); // checks if actual is same label as expected
```

### Faker Provider

[](#faker-provider)

Possibly you are using [faker](https://github.com/FakerPHP/Faker) and want to generate random enums. Because doing so with default faker is a lot of copy'n'paste we've got you covered with a faker provider `Spatie\Enum\Faker\FakerEnumProvider`.

```
use Spatie\Enum\Faker\FakerEnumProvider;
use Faker\Generator as Faker;

/** @var Faker|FakerEnumProvider $faker */
$faker = new Faker();
$faker->addProvider(new FakerEnumProvider($faker));

$enum = $faker->randomEnum(StatusEnum::class);
$value = $faker->randomEnumValue(StatusEnum::class);
$label = $faker->randomEnumLabel(StatusEnum::class);
```

Testing
-------

[](#testing)

```
composer test
```

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.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

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

License
-------

[](#license)

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

###  Health Score

67

—

FairBetter than 100% of packages

Maintenance62

Regular maintenance activity

Popularity72

Solid adoption and visibility

Community45

Growing community involvement

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 50.7% 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 ~26 days

Recently: every ~45 days

Total

46

Last Release

1488d ago

Major Versions

0.0.1 → 1.0.02019-02-08

1.1.0 → 2.0.02019-04-01

v1.x-dev → 2.2.02019-07-18

2.3.8 → 3.0.02020-07-22

v2.x-dev → 3.1.22020-09-28

PHP version history (5 changes)0.0.1PHP ^7.2

3.0.0PHP ^7.4

3.2.0PHP ^7.4|^8.0

3.4.0PHP ^7.4 || ^8.0

3.13.0PHP ^8.0

### 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 (248 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (85 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (41 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (24 commits)")[![Nielsvanpach](https://avatars.githubusercontent.com/u/10651054?v=4)](https://github.com/Nielsvanpach "Nielsvanpach (15 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (15 commits)")[![Nelwhix](https://avatars.githubusercontent.com/u/58360242?v=4)](https://github.com/Nelwhix "Nelwhix (14 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (8 commits)")[![SamMousa](https://avatars.githubusercontent.com/u/547021?v=4)](https://github.com/SamMousa "SamMousa (4 commits)")[![skyrpex](https://avatars.githubusercontent.com/u/1077520?v=4)](https://github.com/skyrpex "skyrpex (3 commits)")[![HergenD](https://avatars.githubusercontent.com/u/32772820?v=4)](https://github.com/HergenD "HergenD (3 commits)")[![msiemens](https://avatars.githubusercontent.com/u/1873922?v=4)](https://github.com/msiemens "msiemens (3 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (3 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (2 commits)")[![b1rdex](https://avatars.githubusercontent.com/u/312855?v=4)](https://github.com/b1rdex "b1rdex (2 commits)")[![tomcoonen](https://avatars.githubusercontent.com/u/988013?v=4)](https://github.com/tomcoonen "tomcoonen (2 commits)")[![bassim](https://avatars.githubusercontent.com/u/748403?v=4)](https://github.com/bassim "bassim (2 commits)")[![timacdonald](https://avatars.githubusercontent.com/u/24803032?v=4)](https://github.com/timacdonald "timacdonald (2 commits)")[![xewl](https://avatars.githubusercontent.com/u/245041?v=4)](https://github.com/xewl "xewl (1 commits)")

---

Tags

enumphpspatieenumenumerable

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[myclabs/php-enum

PHP Enum implementation

2.7k227.9M637](/packages/myclabs-php-enum)[spatie/laravel-package-tools

Tools for creating Laravel packages

945125.5M7.0k](/packages/spatie-laravel-package-tools)[spatie/laravel-data

Create unified resources and data transfer objects

1.8k28.9M627](/packages/spatie-laravel-data)[spatie/laravel-enum

Laravel Enum support

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

A trait to dynamically add methods to a class

72759.6M64](/packages/spatie-macroable)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k17.1M59](/packages/spatie-regex)

PHPackages © 2026

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