{"id":15035290,"url":"https://github.com/bensampo/laravel-enum","last_synced_at":"2025-05-10T07:02:01.329Z","repository":{"id":37733537,"uuid":"102767320","full_name":"BenSampo/laravel-enum","owner":"BenSampo","description":"Simple, extensible and powerful enumeration implementation for Laravel.","archived":false,"fork":false,"pushed_at":"2025-02-25T18:43:47.000Z","size":611,"stargazers_count":2025,"open_issues_count":4,"forks_count":163,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-05-08T20:58:40.507Z","etag":null,"topics":["bitwise-enum","enum","enum-instantiation","enum-library","enumeration","laravel","laravel-enum","laravel-package","php"],"latest_commit_sha":null,"homepage":"https://sampo.co.uk/blog/using-enums-in-laravel","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BenSampo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["bensampo"]}},"created_at":"2017-09-07T17:39:25.000Z","updated_at":"2025-05-02T06:35:24.000Z","dependencies_parsed_at":"2023-11-15T16:28:57.945Z","dependency_job_id":"b3d27312-80a7-4e62-a1e6-471b2052ecd6","html_url":"https://github.com/BenSampo/laravel-enum","commit_stats":{"total_commits":356,"total_committers":54,"mean_commits":6.592592592592593,"dds":0.5056179775280899,"last_synced_commit":"9e281ca6dc22f18c9f64257679bef3117aeb8835"},"previous_names":[],"tags_count":100,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenSampo%2Flaravel-enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenSampo%2Flaravel-enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenSampo%2Flaravel-enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BenSampo%2Flaravel-enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BenSampo","download_url":"https://codeload.github.com/BenSampo/laravel-enum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253157772,"owners_count":21863171,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bitwise-enum","enum","enum-instantiation","enum-library","enumeration","laravel","laravel-enum","laravel-package","php"],"created_at":"2024-09-24T20:28:05.938Z","updated_at":"2025-05-08T22:31:20.968Z","avatar_url":"https://github.com/BenSampo.png","language":"PHP","readme":"\u003cp align=\"center\"\u003e\u003cimg src=\"https://github.com/BenSampo/laravel-enum/raw/master/branding/logo.svg?sanitize=true\" alt=\"Laravel Enum\" width=\"250\" style=\"margin-bottom: 20px\"\u003e\u003c/p\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://packagist.org/packages/bensampo/laravel-enum\"\u003e\u003cimg src=\"https://img.shields.io/packagist/v/bensampo/laravel-enum.svg?style=flat-square\u0026label=stable\" alt=\"Packagist Stable Version\"\u003e\u003c/a\u003e\n\u003ca href=\"https://packagist.org/packages/bensampo/laravel-enum\"\u003e\u003cimg src=\"https://img.shields.io/packagist/dt/bensampo/laravel-enum.svg?style=flat-square\" alt=\"Packagist downloads\"\u003e\u003c/a\u003e\n\u003ca href=\"LICENSE.txt\"\u003e\u003cimg src=\"https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square\" alt=\"MIT Software License\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n## Using this library is no longer recommended\n\nUsing this library is no longer recommended, especially for new projects.\nPHP 8.1 supports enums natively.\n\nSee https://github.com/BenSampo/laravel-enum/issues/332.\n\n## About Laravel Enum\n\nSimple, extensible and powerful enumeration implementation for Laravel.\n\n- Enum key value pairs as class constants\n- Full-featured suite of methods\n- Enum instantiation\n- Flagged/Bitwise enums\n- Type hinting\n- Attribute casting\n- Enum artisan generator\n- Validation rules for passing enum key or values as input parameters\n- Localization support\n- Extendable via Macros\n\nCreated by [Ben Sampson](https://sampo.co.uk)\n\n## Jump To\n\n- [Guide](#guide)\n- [Installation](#installation)\n- [Migrate to Native PHP Enums](#migrate-to-native-PHP-enums)\n- [Enum Library](enum-library.md)\n- [Basic Usage](#basic-usage)\n  - [Enum Definition](#enum-definition)\n  - [Instantiation](#instantiation)\n  - [Instance Properties](#instance-properties)\n  - [Instance Casting](#instance-casting)\n  - [Instance Equality](#instance-equality)\n  - [Type Hinting](#type-hinting)\n- [Flagged/Bitwise Enum](#flaggedbitwise-enum)\n- [Attribute Casting](#attribute-casting)\n- [Migrations](#migrations)\n- [Validation](#validation)\n- [Localization](#localization)\n- [Customizing Descriptions](#customizing-descriptions)\n  - [Customizing Class Description](#customizing-class-description)\n  - [Customizing Value Descriptions](#customizing-value-descriptions)\n- [Extending the Enum Base Class](#extending-the-enum-base-class)\n- [Laravel Nova Integration](#laravel-nova-integration)\n- [PHPStan Integration](#phpstan-integration)\n- [Artisan Command List](#artisan-command-list)\n- [Enum Class Reference](#enum-class-reference)\n- [Stubs](#stubs)\n\n## Documentation for older versions\n\nYou are reading the documentation for `6.x`.\n\n- If you're using **Laravel 8** please see the [docs for `4.x`](https://github.com/BenSampo/laravel-enum/blob/v4.2.0/README.md).\n- If you're using **Laravel 7** please see the [docs for `2.x`](https://github.com/BenSampo/laravel-enum/blob/v2.2.0/README.md).\n- If you're using **Laravel 6** or below, please see the [docs for `1.x`](https://github.com/BenSampo/laravel-enum/blob/v1.38.0/README.md).\n\nPlease see the [upgrade guide](UPGRADE.md) for information on how to upgrade to the latest version.\n\n## Guide\n\nI wrote a blog post about using laravel-enum: https://sampo.co.uk/blog/using-enums-in-laravel\n\n## Installation\n\nRequires PHP 8, and Laravel 9 or 10.\n\n```sh\ncomposer require bensampo/laravel-enum\n```\n\n## Migrate to Native PHP Enums\n\nPHP 8.1 supports enums natively.\nYou can migrate your usages of `BenSampo\\Enum\\Enum` to native PHP enums using the following steps.\n\nMake sure you meet the following requirements:\n- PHP 8.1 or higher\n- Laravel 10 or higher\n- Rector 0.17 or higher, your `rector.php` includes all relevant files\n- Latest version of this library\n\nDepending on the size of your project, you may choose to migrate all enums at once,\nor migrate just a couple or one enum at a time.\n- Convert all enums at once: `php artisan enum:to-native`\n- Pass the fully qualified class name of an enum to limit the conversion: `php artisan enum:to-native \"App\\Enums\\UserType\"`\n\n  This is necessary if any enums are used during the bootstrap phase of Laravel,\n  the conversion of their usages interferes with Larastan and prevents a second run of Rector from working.\n\nReview and validate the code changes for missed edge cases:\n- See [Unimplemented](tests/Rector/Unimplemented)\n- `Enum::coerce()`: If only values were passed, you can replace it with `tryFrom()`.\n   If keys or instances could also be passed, you might need additional logic to cover this.\n- `Enum::$description` and `Enum::getDescription()`: Implement an alternative.\n- try/catch-blocks that handle `BenSampo\\Enum\\Exceptions\\InvalidEnumKeyException` or `BenSampo\\Enum\\Exceptions\\InvalidEnumMemberException`.\n  Either catch the `ValueError` thrown by native enums, or switch to using `tryFrom()` and handle `null`.\n\nOnce all enums are converted, you can remove your dependency on this library.\n\n## Enum Library\n\nBrowse and download from a list of commonly used, community contributed enums.\n\n[Enum library →](enum-library.md)\n\n## Basic Usage\n\n### Enum Definition\n\nYou can use the following Artisan command to generate a new enum class:\n\n```php\nphp artisan make:enum UserType\n```\n\nNow, you just need to add the possible values your enum can have as constants.\n\n```php\n\u003c?php declare(strict_types=1);\n\nnamespace App\\Enums;\n\nuse BenSampo\\Enum\\Enum;\n\nfinal class UserType extends Enum\n{\n    const Administrator = 0;\n    const Moderator = 1;\n    const Subscriber = 2;\n    const SuperAdministrator = 3;\n}\n```\n\nThat's it! Note that because the enum values are defined as plain constants,\nyou can simply access them like any other class constant.\n\n```php\nUserType::Administrator // Has a value of 0\n```\n\n### Instantiation\n\nIt can be useful to instantiate enums in order to pass them between functions\nwith the benefit of type hinting.\n\nAdditionally, it's impossible to instantiate an enum with an invalid value,\ntherefore you can be certain that the passed value is always valid.\n\nFor convenience, enums can be instantiated in multiple ways:\n\n```php\n// Standard new PHP class, passing the desired enum value as a parameter\n$enumInstance = new UserType(UserType::Administrator);\n\n// Same as the constructor, instantiate by value\n$enumInstance = UserType::fromValue(UserType::Administrator);\n\n// Use an enum key instead of its value\n$enumInstance = UserType::fromKey('Administrator');\n\n// Statically calling the key name as a method, utilizing __callStatic magic\n$enumInstance = UserType::Administrator();\n\n// Attempt to instantiate a new Enum using the given key or value. Returns null if the Enum cannot be instantiated.\n$enumInstance = UserType::coerce($someValue);\n```\n\nIf you want your IDE to autocomplete the static instantiation helpers, you can\ngenerate PHPDoc annotations through an artisan command.\n\nBy default, all Enums in `app/Enums` will be annotated (you can change the folder by passing a path to `--folder`).\n\n```sh\nphp artisan enum:annotate\n```\n\nYou can annotate a single class by specifying the class name.\n\n```sh\nphp artisan enum:annotate \"App\\Enums\\UserType\"\n```\n\n### Instance Properties\n\nOnce you have an enum instance, you can access the `key`, `value` and `description` as properties.\n\n```php\n$userType = UserType::fromValue(UserType::SuperAdministrator);\n\n$userType-\u003ekey; // SuperAdministrator\n$userType-\u003evalue; // 3\n$userType-\u003edescription; // Super Administrator\n```\n\nThis is particularly useful if you're passing an enum instance to a blade view.\n\n### Instance Casting\n\nEnum instances can be cast to strings as they implement the `__toString()` magic method.  \nThis also means they can be echoed in blade views, for example.\n\n```php\n$userType = UserType::fromValue(UserType::SuperAdministrator);\n\n(string) $userType // '3'\n```\n\n### Instance Equality\n\nYou can check the equality of an instance against any value by passing it to the `is` method.\nFor convenience, there is also an `isNot` method which is the exact reverse of the `is` method.\n\n```php\n$admin = UserType::Administrator();\n\n$admin-\u003eis(UserType::Administrator);   // true\n$admin-\u003eis($admin);                    // true\n$admin-\u003eis(UserType::Administrator()); // true\n\n$admin-\u003eis(UserType::Moderator);       // false\n$admin-\u003eis(UserType::Moderator());     // false\n$admin-\u003eis('random-value');            // false\n```\n\nYou can also check to see if the instance's value matches against an array of possible values using the `in` method,\nand use `notIn` to check if instance value is not in an array of values.\nIterables can also be checked against.\n\n```php\n$admin = UserType::Administrator();\n\n$admin-\u003ein([UserType::Moderator, UserType::Administrator]);     // true\n$admin-\u003ein([UserType::Moderator(), UserType::Administrator()]); // true\n\n$admin-\u003ein([UserType::Moderator, UserType::Subscriber]);        // false\n$admin-\u003ein(['random-value']);                                   // false\n\n$admin-\u003enotIn([UserType::Moderator, UserType::Administrator]);     // false\n$admin-\u003enotIn([UserType::Moderator(), UserType::Administrator()]); // false\n\n$admin-\u003enotIn([UserType::Moderator, UserType::Subscriber]);        // true\n$admin-\u003enotIn(['random-value']);                                   // true\n```\n\nThe instantiated enums are not singletons, rather a new object is created every time.\nThus, strict comparison `===` of different enum instances will always return `false`, no matter the value.\nIn contrast, loose comparison `==` will depend on the value.\n\n```php\n$admin = UserType::Administrator();\n\n$admin === UserType::Administrator();                    // false\nUserType::Administrator() === UserType::Administrator(); // false\n$admin === UserType::Moderator();                        // false\n\n$admin === $admin;                                       // true\n\n$admin == UserType::Administrator(); // true\n$admin == UserType::Administrator;   // true\n\n$admin == UserType::Moderator();     // false\n$admin == UserType::Moderator;       // false\n```\n\n### Type Hinting\n\nOne of the benefits of enum instances is that it enables you to use type hinting, as shown below.\n\n```php\nfunction canPerformAction(UserType $userType)\n{\n    if ($userType-\u003eis(UserType::SuperAdministrator)) {\n        return true;\n    }\n\n    return false;\n}\n\n$userType1 = UserType::fromValue(UserType::SuperAdministrator);\n$userType2 = UserType::fromValue(UserType::Moderator);\n\ncanPerformAction($userType1); // Returns true\ncanPerformAction($userType2); // Returns false\n```\n\n## Flagged/Bitwise Enum\n\nStandard enums represent a single value at a time, but flagged or bitwise enums are capable of of representing multiple values simultaneously. This makes them perfect for when you want to express multiple selections of a limited set of options. A good example of this would be user permissions where there are a limited number of possible permissions but a user can have none, some or all of them.\n\nYou can create a flagged enum using the following artisan command:\n\n`php artisan make:enum UserPermissions --flagged`\n\n### Defining values\n\nWhen defining values you must use powers of 2, the easiest way to do this is by using the _shift left_ `\u003c\u003c` operator like so:\n\n```php\nfinal class UserPermissions extends FlaggedEnum\n{\n    const ReadComments      = 1 \u003c\u003c 0;\n    const WriteComments     = 1 \u003c\u003c 1;\n    const EditComments      = 1 \u003c\u003c 2;\n    const DeleteComments    = 1 \u003c\u003c 3;\n    // The next one would be `1 \u003c\u003c 4` and so on...\n}\n```\n\n### Defining shortcuts\n\nYou can use the bitwise _or_ `|` to set a shortcut value which represents a given set of values.\n\n```php\nfinal class UserPermissions extends FlaggedEnum\n{\n    const ReadComments      = 1 \u003c\u003c 0;\n    const WriteComments     = 1 \u003c\u003c 1;\n    const EditComments      = 1 \u003c\u003c 2;\n    const DeleteComments    = 1 \u003c\u003c 3;\n\n    // Shortcuts\n    const Member = self::ReadComments | self::WriteComments; // Read and write.\n    const Moderator = self::Member | self::EditComments; // All the permissions a Member has, plus Edit.\n    const Admin = self::Moderator | self::DeleteComments; // All the permissions a Moderator has, plus Delete.\n}\n```\n\n### Instantiating a flagged enum\n\nThere are couple of ways to instantiate a flagged enum:\n\n```php\n// Standard new PHP class, passing the desired enum values as an array of values or array of enum instances\n$permissions = new UserPermissions([UserPermissions::ReadComments, UserPermissions::EditComments]);\n$permissions = new UserPermissions([UserPermissions::ReadComments(), UserPermissions::EditComments()]);\n\n// Static flags method, again passing the desired enum values as an array of values or array of enum instances\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::EditComments]);\n$permissions = UserPermissions::flags([UserPermissions::ReadComments(), UserPermissions::EditComments()]);\n```\n\n[Attribute casting](#attribute-casting) works in the same way as single value enums.\n\n### Empty flagged enums\n\nFlagged enums can contain no value at all. Every flagged enum has a pre-defined constant of `None` which is comparable to `0`.\n\n```php\nUserPermissions::flags([])-\u003evalue === UserPermissions::None; // True\n```\n\n### Flagged enum methods\n\nIn addition to the standard enum methods, there are a suite of helpful methods available on flagged enums.\n\nNote: Anywhere where a static property is passed, you can also pass an enum instance.\n\n#### setFlags(array $flags): Enum\n\nSet the flags for the enum to the given array of flags.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments]);\n$permissions-\u003eflags([UserPermissions::EditComments, UserPermissions::DeleteComments]); // Flags are now: EditComments, DeleteComments.\n```\n\n#### addFlag($flag): Enum\n\nAdd the given flag to the enum\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments]);\n$permissions-\u003eaddFlag(UserPermissions::EditComments); // Flags are now: ReadComments, EditComments.\n```\n\n#### addFlags(array $flags): Enum\n\nAdd the given flags to the enum\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments]);\n$permissions-\u003eaddFlags([UserPermissions::EditComments, UserPermissions::WriteComments]); // Flags are now: ReadComments, EditComments, WriteComments.\n```\n\n#### addAllFlags(): Enum\n\nAdd all flags to the enum\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments]);\n$permissions-\u003eaddAllFlags(); // Enum now has all flags\n```\n\n#### removeFlag($flag): Enum\n\nRemove the given flag from the enum\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003eremoveFlag(UserPermissions::ReadComments); // Flags are now: WriteComments.\n```\n\n#### removeFlags(array $flags): Enum\n\nRemove the given flags from the enum\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments, UserPermissions::EditComments]);\n$permissions-\u003eremoveFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // Flags are now: EditComments.\n```\n\n#### removeAllFlags(): Enum\n\nRemove all flags from the enum\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003eremoveAllFlags();\n```\n\n#### hasFlag($flag): bool\n\nCheck if the enum has the specified flag.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003ehasFlag(UserPermissions::ReadComments); // True\n$permissions-\u003ehasFlag(UserPermissions::EditComments); // False\n```\n\n#### hasFlags(array $flags): bool\n\nCheck if the enum has all of the specified flags.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003ehasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // True\n$permissions-\u003ehasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // False\n```\n\n#### notHasFlag($flag): bool\n\nCheck if the enum does not have the specified flag.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003enotHasFlag(UserPermissions::EditComments); // True\n$permissions-\u003enotHasFlag(UserPermissions::ReadComments); // False\n```\n\n#### notHasFlags(array $flags): bool\n\nCheck if the enum doesn't have any of the specified flags.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003enotHasFlags([UserPermissions::ReadComments, UserPermissions::EditComments]); // True\n$permissions-\u003enotHasFlags([UserPermissions::ReadComments, UserPermissions::WriteComments]); // False\n```\n\n#### getFlags(): Enum[]\n\nReturn the flags as an array of instances.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003egetFlags(); // [UserPermissions::ReadComments(), UserPermissions::WriteComments()];\n```\n\n#### hasMultipleFlags(): bool\n\nCheck if there are multiple flags set on the enum.\n\n```php\n$permissions = UserPermissions::flags([UserPermissions::ReadComments, UserPermissions::WriteComments]);\n$permissions-\u003ehasMultipleFlags(); // True;\n$permissions-\u003eremoveFlag(UserPermissions::ReadComments)-\u003ehasMultipleFlags(); // False\n```\n\n#### getBitmask(): int\n\nGet the bitmask for the enum.\n\n```php\nUserPermissions::Member()-\u003egetBitmask(); // 11;\nUserPermissions::Moderator()-\u003egetBitmask(); // 111;\nUserPermissions::Admin()-\u003egetBitmask(); // 1111;\nUserPermissions::DeleteComments()-\u003egetBitmask(); // 1000;\n```\n\n### Flagged enums in Eloquent queries\n\nTo use flagged enums directly in your Eloquent queries, you may use the `QueriesFlaggedEnums` trait on your model which provides you with the following methods:\n\n#### hasFlag($column, $flag): Builder\n\n```php\nUser::hasFlag('permissions', UserPermissions::DeleteComments())-\u003eget();\n```\n\n#### notHasFlag($column, $flag): Builder\n\n```php\nUser::notHasFlag('permissions', UserPermissions::DeleteComments())-\u003eget();\n```\n\n#### hasAllFlags($column, $flags): Builder\n\n```php\nUser::hasAllFlags('permissions', [UserPermissions::EditComment(), UserPermissions::ReadComment()])-\u003eget();\n```\n\n#### hasAnyFlags($column, $flags): Builder\n\n```php\nUser::hasAnyFlags('permissions', [UserPermissions::DeleteComments(), UserPermissions::EditComments()])-\u003eget();\n```\n\n## Attribute Casting\n\nYou may cast model attributes to enums using Laravel's built in custom casting. This will cast the attribute to an enum instance when getting and back to the enum value when setting.\nSince `Enum::class` implements the `Castable` contract, you just need to specify the classname of the enum:\n\n```php\nuse BenSampo\\Enum\\Tests\\Enums\\UserType;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Example extends Model\n{\n    protected $casts = [\n        'random_flag' =\u003e 'boolean',     // Example standard laravel cast\n        'user_type' =\u003e UserType::class, // Example enum cast\n    ];\n}\n```\n\nNow, when you access the `user_type` attribute of your `Example` model,\nthe underlying value will be returned as a `UserType` enum.\n\n```php\n$example = Example::first();\n$example-\u003euser_type // Instance of UserType\n```\n\nReview the [methods and properties available on enum instances](#instantiation) to get the most out of attribute casting.\n\nYou can set the value by either passing the enum value or another enum instance.\n\n```php\n$example = Example::first();\n\n// Set using enum value\n$example-\u003euser_type = UserType::Moderator;\n\n// Set using enum instance\n$example-\u003euser_type = UserType::Moderator();\n```\n\n### Customising `$model-\u003etoArray()` behaviour\n\nWhen using `toArray` (or returning model/models from your controller as a response) Laravel will call the `toArray` method on the enum instance.\n\nBy default, this will return only the value in its native type. You may want to also have access to the other properties (key, description), for example to return\nto javascript app.\n\nTo customise this behaviour, you can override the `toArray` method on the enum instance.\n\n```php\n// Example Enum\nfinal class UserType extends Enum\n{\n    const ADMINISTRATOR = 0;\n    const MODERATOR = 1;\n}\n\n$instance = UserType::Moderator();\n\n// Default\npublic function toArray()\n{\n    return $this-\u003evalue;\n}\n// Returns int(1)\n\n// Return all properties\npublic function toArray()\n{\n    return $this;\n}\n// Returns an array of all the properties\n// array(3) {\n//  [\"value\"]=\u003e\n//  int(1)\"\n//  [\"key\"]=\u003e\n//  string(9) \"MODERATOR\"\n//  [\"description\"]=\u003e\n//  string(9) \"Moderator\"\n// }\n\n```\n\n### Casting underlying native types\n\nMany databases return everything as strings (for example, an integer may be returned as the string `'1'`).\nTo reduce friction for users of the library, we use type coercion to figure out the intended value. If you'd prefer to control this, you can override the `parseDatabase` static method on your enum class:\n\n```php\nfinal class UserType extends Enum\n{\n    const Administrator = 0;\n    const Moderator = 1;\n\n    public static function parseDatabase($value)\n    {\n        return (int) $value;\n    }\n}\n```\n\nReturning `null` from the `parseDatabase` method will cause the attribute on the model to also be `null`. This can be useful if your database stores inconsistent blank values such as empty strings instead of `NULL`.\n\n### Model Annotation\n\nIf you're casting attributes on your model to enums, the [laravel-ide-helper](https://github.com/barryvdh/laravel-ide-helper) package can be used to automatically generate property docblocks for you.\n\n## Migrations\n\n### Recommended\n\nBecause enums enforce consistency at the code level it's not necessary to do so again at the database level, therefore the recommended type for database columns is `string` or `int` depending on your enum values. This means you can add/remove enum values in your code without worrying about your database layer.\n\n```php\nuse App\\Enums\\UserType;\nuse Illuminate\\Support\\Facades\\Schema;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Database\\Migrations\\Migration;\n\nclass CreateUsersTable extends Migration\n{\n    /**\n     * Run the migrations.\n     *\n     * @return void\n     */\n    public function up(): void\n    {\n        Schema::table('users', function (Blueprint $table): void {\n            $table-\u003ebigIncrements('id');\n            $table-\u003etimestamps();\n            $table-\u003estring('type')\n                -\u003edefault(UserType::Moderator);\n        });\n    }\n}\n```\n\n### Using `enum` column type\n\nAlternatively you may use `Enum` classes in your migrations to define enum columns.\nThe enum values must be defined as strings.\n\n```php\nuse App\\Enums\\UserType;\nuse Illuminate\\Support\\Facades\\Schema;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Database\\Migrations\\Migration;\n\nclass CreateUsersTable extends Migration\n{\n    /**\n     * Run the migrations.\n     *\n     * @return void\n     */\n    public function up(): void\n    {\n        Schema::table('users', function (Blueprint $table): void {\n            $table-\u003ebigIncrements('id');\n            $table-\u003etimestamps();\n            $table-\u003eenum('type', UserType::getValues())\n                -\u003edefault(UserType::Moderator);\n        });\n    }\n}\n```\n\n## Validation\n\n### Array Validation\n\n#### Enum value\n\nYou may validate that an enum value passed to a controller is a valid value for a given enum by using the `EnumValue` rule.\n\n```php\nuse BenSampo\\Enum\\Rules\\EnumValue;\n\npublic function store(Request $request)\n{\n    $this-\u003evalidate($request, [\n        'user_type' =\u003e ['required', new EnumValue(UserType::class)],\n    ]);\n}\n```\n\nBy default, type checking is set to strict, but you can bypass this by passing `false` to the optional second parameter of the EnumValue class.\n\n```php\nnew EnumValue(UserType::class, false) // Turn off strict type checking.\n```\n\n#### Enum key\n\nYou can also validate on keys using the `EnumKey` rule. This is useful if you're taking the enum key as a URL parameter for sorting or filtering for example.\n\n```php\nuse BenSampo\\Enum\\Rules\\EnumKey;\n\npublic function store(Request $request)\n{\n    $this-\u003evalidate($request, [\n        'user_type' =\u003e ['required', new EnumKey(UserType::class)],\n    ]);\n}\n```\n\n#### Enum instance\n\nAdditionally you can validate that a parameter is an instance of a given enum.\n\n```php\nuse BenSampo\\Enum\\Rules\\Enum;\n\npublic function store(Request $request)\n{\n    $this-\u003evalidate($request, [\n        'user_type' =\u003e ['required', new Enum(UserType::class)],\n    ]);\n}\n```\n\n### Pipe Validation\n\nYou can also use the 'pipe' syntax for rules.\n\n**enum_value**_:enum_class,[strict]_  \n**enum_key**_:enum_class_  \n**enum**_:enum_class_\n\n```php\n'user_type' =\u003e 'required|enum_value:' . UserType::class,\n'user_type' =\u003e 'required|enum_key:' . UserType::class,\n'user_type' =\u003e 'required|enum:' . UserType::class,\n```\n\n## Localization\n\n### Validation messages\n\nRun the following command to publish the language files to your `lang` folder.\n\n```\nphp artisan vendor:publish --provider=\"BenSampo\\Enum\\EnumServiceProvider\" --tag=\"translations\"\n```\n\n### Enum descriptions\n\nYou can translate the strings returned by the `getDescription` method using Laravel's built-in [localization](https://laravel.com/docs/localization) features.\n\nAdd a new `enums.php` keys file for each of your supported languages. In this example there is one for English and one for Spanish.\n\n```php\n// lang/en/enums.php\n\u003c?php declare(strict_types=1);\n\nuse App\\Enums\\UserType;\n\nreturn [\n\n    UserType::class =\u003e [\n        UserType::Administrator =\u003e 'Administrator',\n        UserType::SuperAdministrator =\u003e 'Super administrator',\n    ],\n\n];\n```\n\n```php\n// lang/es/enums.php\n\u003c?php declare(strict_types=1);\n\nuse App\\Enums\\UserType;\n\nreturn [\n\n    UserType::class =\u003e [\n        UserType::Administrator =\u003e 'Administrador',\n        UserType::SuperAdministrator =\u003e 'Súper administrador',\n    ],\n\n];\n```\n\nNow, you just need to make sure that your enum implements the `LocalizedEnum` interface as demonstrated below:\n\n```php\nuse BenSampo\\Enum\\Enum;\nuse BenSampo\\Enum\\Contracts\\LocalizedEnum;\n\nfinal class UserType extends Enum implements LocalizedEnum\n{\n    // ...\n}\n```\n\nThe `getDescription` method will now look for the value in your localization files. If a value doesn't exist for a given key, the default description is returned instead.\n\n## Customizing descriptions\n\n### Customizing class description\n\nIf you'd like to return a custom description for your enum class, add a `Description` attribute to your Enum class:\n\n```php\nuse BenSampo\\Enum\\Enum;\nuse BenSampo\\Enum\\Attributes\\Description;\n\n#[Description('List of available User types')]\nfinal class UserType extends Enum\n{\n    ...\n}\n```\n\nCalling `UserType::getClassDescription()` now returns `List of available User types` instead of `User type`.\n\nYou may also override the `getClassDescription` method on the base Enum class if you wish to have more control of the description.\n\n### Customizing value descriptions\n\nIf you'd like to return a custom description for your enum values, add a `Description` attribute to your Enum constants:\n\n```php\nuse BenSampo\\Enum\\Enum;\nuse BenSampo\\Enum\\Attributes\\Description;\n\nfinal class UserType extends Enum\n{\n    const Administrator = 'Administrator';\n\n    #[Description('Super admin')]\n    const SuperAdministrator = 'SuperAdministrator';\n}\n```\n\nCalling `UserType::SuperAdministrator()-\u003edescription` now returns `Super admin` instead of `Super administrator`.\n\nYou may also override the `getDescription` method on the base Enum class if you wish to have more control of the description.\n\n## Extending the Enum Base Class\n\nThe `Enum` base class implements the [Laravel `Macroable`](https://laravel.com/api/9.x/Illuminate/Support/Traits/Macroable.html) trait, meaning it's easy to extend it with your own functions. If you have a function that you often add to each of your enums, you can use a macro.\n\nLet's say we want to be able to get a flipped version of the enum `asArray` method, we can do this using:\n\n```php\nEnum::macro('asFlippedArray', function() {\n    return array_flip(self::asArray());\n});\n```\n\nNow, on each of my enums, I can call it using `UserType::asFlippedArray()`.\n\nIt's best to register the macro inside a service providers' boot method.\n\n## Laravel Nova Integration\n\nUse the [nova-enum-field](https://github.com/simplesquid/nova-enum-field) package by Simple Squid to easily create fields for your Enums in Nova. See their readme for usage.\n\n## PHPStan Integration\n\nIf you are using [PHPStan](https://github.com/phpstan/phpstan) for static analysis, enable the extension for:\n- proper recognition of the magic instantiation methods\n- detection of duplicate enum values\n\nUse [PHPStan Extension Installer](https://github.com/phpstan/extension-installer) or add the following to your projects `phpstan.neon` includes:\n\n```neon\nincludes:\n- vendor/bensampo/laravel-enum/extension.neon\n```\n\n## Artisan Command List\n\n### `php artisan make:enum`\n\nCreate a new enum class. Pass `--flagged` as an option to create a flagged enum.  \n[Find out more](#enum-definition)\n\n### `php artisan enum:annotate`\n\nGenerate DocBlock annotations for enum classes.  \n[Find out more](#instantiation)\n\n### `php artisan enum:to-native`\n\nSee [migrate to native PHP enums](#migrate-to-native-php-enums).\n\n## Enum Class Reference\n\n### static getKeys(mixed $values = null): array\n\nReturns an array of all or a custom set of the keys for an enum.\n\n```php\nUserType::getKeys(); // Returns ['Administrator', 'Moderator', 'Subscriber', 'SuperAdministrator']\nUserType::getKeys(UserType::Administrator); // Returns ['Administrator']\nUserType::getKeys(UserType::Administrator, UserType::Moderator); // Returns ['Administrator', 'Moderator']\nUserType::getKeys([UserType::Administrator, UserType::Moderator]); // Returns ['Administrator', 'Moderator']\n```\n\n### static getValues(mixed $keys = null): array\n\nReturns an array of all or a custom set of the values for an enum.\n\n```php\nUserType::getValues(); // Returns [0, 1, 2, 3]\nUserType::getValues('Administrator'); // Returns [0]\nUserType::getValues('Administrator', 'Moderator'); // Returns [0, 1]\nUserType::getValues(['Administrator', 'Moderator']); // Returns [0, 1]\n```\n\n### static getKey(mixed $value): string\n\nReturns the key for the given enum value.\n\n```php\nUserType::getKey(1); // Returns 'Moderator'\nUserType::getKey(UserType::Moderator); // Returns 'Moderator'\n```\n\n### static getValue(string $key): mixed\n\nReturns the value for the given enum key.\n\n```php\nUserType::getValue('Moderator'); // Returns 1\n```\n\n### static hasKey(string $key): bool\n\nCheck if the enum contains a given key.\n\n```php\nUserType::hasKey('Moderator'); // Returns 'True'\n```\n\n### static hasValue(mixed $value, bool $strict = true): bool\n\nCheck if the enum contains a given value.\n\n```php\nUserType::hasValue(1); // Returns 'True'\n\n// It's possible to disable the strict type checking:\nUserType::hasValue('1'); // Returns 'False'\nUserType::hasValue('1', false); // Returns 'True'\n```\n\n### static getClassDescription(): string\n\nReturns the class name in sentence case for the enum class. It's possible to [customize the description](#customizing-descriptions) if the guessed description is not appropriate.\n\n```php\nUserType::getClassDescription(); // Returns 'User type'\n```\n\n### static getDescription(mixed $value): string\n\nReturns the key in sentence case for the enum value. It's possible to [customize the description](#customizing-descriptions) if the guessed description is not appropriate.\n\n```php\nUserType::getDescription(3); // Returns 'Super administrator'\nUserType::getDescription(UserType::SuperAdministrator); // Returns 'Super administrator'\n```\n\n### static getRandomKey(): string\n\nReturns a random key from the enum. Useful for factories.\n\n```php\nUserType::getRandomKey(); // Returns 'Administrator', 'Moderator', 'Subscriber' or 'SuperAdministrator'\n```\n\n### static getRandomValue(): mixed\n\nReturns a random value from the enum. Useful for factories.\n\n```php\nUserType::getRandomValue(); // Returns 0, 1, 2 or 3\n```\n\n### static getRandomInstance(): mixed\n\nReturns a random instance of the enum. Useful for factories.\n\n```php\nUserType::getRandomInstance(); // Returns an instance of UserType with a random value\n```\n\n### static asArray(): array\n\nReturns the enum key value pairs as an associative array.\n\n```php\nUserType::asArray(); // Returns ['Administrator' =\u003e 0, 'Moderator' =\u003e 1, 'Subscriber' =\u003e 2, 'SuperAdministrator' =\u003e 3]\n```\n\n### static asSelectArray(): array\n\nReturns the enum for use in a select as value =\u003e description.\n\n```php\nUserType::asSelectArray(); // Returns [0 =\u003e 'Administrator', 1 =\u003e 'Moderator', 2 =\u003e 'Subscriber', 3 =\u003e 'Super administrator']\n```\n\n### static fromValue(mixed $enumValue): Enum\n\nReturns an instance of the called enum. Read more about [enum instantiation](#instantiation).\n\n```php\nUserType::fromValue(UserType::Administrator); // Returns instance of Enum with the value set to UserType::Administrator\n```\n\n### static getInstances(): array\n\nReturns an array of all possible instances of the called enum, keyed by the constant names.\n\n```php\nvar_dump(UserType::getInstances());\n\narray(4) {\n  'Administrator' =\u003e\n  class BenSampo\\Enum\\Tests\\Enums\\UserType#415 (3) {\n    public $key =\u003e\n    string(13) \"Administrator\"\n    public $value =\u003e\n    int(0)\n    public $description =\u003e\n    string(13) \"Administrator\"\n  }\n  'Moderator' =\u003e\n  class BenSampo\\Enum\\Tests\\Enums\\UserType#396 (3) {\n    public $key =\u003e\n    string(9) \"Moderator\"\n    public $value =\u003e\n    int(1)\n    public $description =\u003e\n    string(9) \"Moderator\"\n  }\n  'Subscriber' =\u003e\n  class BenSampo\\Enum\\Tests\\Enums\\UserType#393 (3) {\n    public $key =\u003e\n    string(10) \"Subscriber\"\n    public $value =\u003e\n    int(2)\n    public $description =\u003e\n    string(10) \"Subscriber\"\n  }\n  'SuperAdministrator' =\u003e\n  class BenSampo\\Enum\\Tests\\Enums\\UserType#102 (3) {\n    public $key =\u003e\n    string(18) \"SuperAdministrator\"\n    public $value =\u003e\n    int(3)\n    public $description =\u003e\n    string(19) \"Super administrator\"\n  }\n}\n```\n\n### static coerce(mixed $enumKeyOrValue): ?Enum\n\nAttempt to instantiate a new Enum using the given key or value. Returns null if the Enum cannot be instantiated.\n\n```php\nUserType::coerce(0); // Returns instance of UserType with the value set to UserType::Administrator\nUserType::coerce('Administrator'); // Returns instance of UserType with the value set to UserType::Administrator\nUserType::coerce(99); // Returns null (not a valid enum value)\n```\n\n## Stubs\n\nRun the following command to publish the stub files to the `stubs` folder in the root of your application.\n\n```shell\nphp artisan vendor:publish --provider=\"BenSampo\\Enum\\EnumServiceProvider\" --tag=\"stubs\"\n```\n","funding_links":["https://github.com/sponsors/bensampo"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbensampo%2Flaravel-enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbensampo%2Flaravel-enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbensampo%2Flaravel-enum/lists"}