{"id":19651406,"url":"https://github.com/sourceboat/laravel-enumeration","last_synced_at":"2025-06-17T04:35:29.411Z","repository":{"id":37927310,"uuid":"173816565","full_name":"sourceboat/laravel-enumeration","owner":"sourceboat","description":"Enum implementation for Laravel.","archived":false,"fork":false,"pushed_at":"2023-01-09T16:03:14.000Z","size":189,"stargazers_count":9,"open_issues_count":1,"forks_count":1,"subscribers_count":5,"default_branch":"develop","last_synced_at":"2025-05-23T02:40:59.238Z","etag":null,"topics":["hacktoberfest","laravel","php"],"latest_commit_sha":null,"homepage":"","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/sourceboat.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-04T20:30:26.000Z","updated_at":"2023-04-21T21:48:37.000Z","dependencies_parsed_at":"2023-02-08T12:46:22.563Z","dependency_job_id":null,"html_url":"https://github.com/sourceboat/laravel-enumeration","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"purl":"pkg:github/sourceboat/laravel-enumeration","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceboat%2Flaravel-enumeration","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceboat%2Flaravel-enumeration/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceboat%2Flaravel-enumeration/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceboat%2Flaravel-enumeration/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sourceboat","download_url":"https://codeload.github.com/sourceboat/laravel-enumeration/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceboat%2Flaravel-enumeration/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260294085,"owners_count":22987596,"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":["hacktoberfest","laravel","php"],"created_at":"2024-11-11T15:06:28.334Z","updated_at":"2025-06-17T04:35:29.388Z","avatar_url":"https://github.com/sourceboat.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# laravel-enumeration\n\n[![Tests](https://github.com/sourceboat/laravel-enumeration/actions/workflows/test.yaml/badge.svg?branch=develop)](https://github.com/sourceboat/laravel-enumeration/actions/workflows/test.yaml)\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/sourceboat/laravel-enumeration.svg?style=flat-square)](https://packagist.org/packages/sourceboat/laravel-enumeration)\n[![Packagist Stable Version](https://img.shields.io/packagist/v/sourceboat/laravel-enumeration.svg?style=flat-square\u0026label=stable)](https://packagist.org/packages/sourceboat/laravel-enumeration)\n[![Packagist downloads](https://img.shields.io/packagist/dt/sourceboat/laravel-enumeration.svg?style=flat-square)](https://packagist.org/packages/sourceboat/laravel-enumeration)\n[![MIT Software License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE.md)\n\nEnum implementation for Laravel. Based on [eloquent/enumeration](https://github.com/eloquent/enumeration) and inspired by [bensampo/laravel-enum](https://github.com/bensampo/laravel-enum)\n\n## Features\n\n* Key/value-definition via class constants\n* Full featured suite of methods\n* Enum artisan generator\n* Validation rules for passing enum values as input parameters\n* Localization support\n* Support to give enum Members a weight\n* Extensible\n\n## Table of Contents\n\n* [Requirements](#requirements)\n* [Install](#install)\n* [Generating enums](#generating-enums)\n* [Usage](#usage)\n* [Methods](#methods)\n* [Validation](#validation)\n* [Localization](#localization)\n* [Custom cast](#custom-cast)\n* [Weighted Enums](#weighted-enums)\n* [License information](#license-information)\n\n## Requirements\n\n* Laravel 8.0 or newer;\n* PHP 7.3 or newer\n\n## Install\n\nVia Composer\n\n``` bash\ncomposer require sourceboat/laravel-enumeration\n```\n\n## Generating enums\n\n```php\nphp artisan make:enum UserType\n```\n\n## Usage\n\nGiven the following enum:\n\n``` php\n\u003c?php\n\nnamespace App\\Enums;\n\nuse Sourceboat\\Enumeration\\Enumeration;\n\n/**\n * @method static \\App\\Enums\\UserType Administrator() // These are only for autocompletion etc.\n * @method static \\App\\Enums\\UserType Moderator()\n * @method static \\App\\Enums\\UserType Subscriber()\n * @method static \\App\\Enums\\UserType SuperAdministrator()\n */\nfinal class UserType extends Enumeration\n{\n    const Administrator = 0;\n    const Moderator = 1;\n    const Subscriber = 2;\n    const SuperAdministrator = 3;\n}\n```\n\nValues can now be accessed like so:\n\n``` php\nUserType::Moderator() // Returns an instance of UserType with UserType::Moderator()-\u003evalue === 1\n```\n\n## Methods\n\n### static keys(): array\n\nReturns an array of the keys for an enumeration.\n\n``` php\nUserType::keys(); // Returns ['Administrator', 'Moderator', 'Subscriber', 'SuperAdministrator']\n```\n\n### static values(): array\n\nReturns an array of the values for an enum.\n\n``` php\nUserType::values(); // Returns [0, 1, 2, 3]\n```\n\n### key(): string\n\nReturns the key for the given enum value.\n\n``` php\nUserType::Moderator()-\u003ekey(); // Returns 'Moderator'\n```\n\n### value(): mixed\n\nReturns the value for the given enum key.\n\n``` php\nUserType::Moderator()-\u003evalue(); // Returns 1\n```\n\n### localized(): string\n\nReturns the localized version of the value, default path is `enums.\u003cEnumClass\u003e.\u003cEnumValue\u003e`, path can be overridden by setting `protected static $localizationPath`.\n\n``` php\nUserType::SuperAdministrator()-\u003elocalized(); // Returns for example 'Super Administrator', but `enums.App\\Enums\\UserType.3` when not set.\n```\n\n### is(static): bool\n\nCheck if the instance is equal to the given member.\n\n``` php\nUserType::SuperAdministrator()-\u003eis(UserType::Moderator()); // -\u003e false\nUserType::SuperAdministrator()-\u003eis(UserType::SuperAdministrator()); // -\u003e true\n```\n\n### is\u003cEnum_Value\u003e(): bool\n\nCheck if the instance is equal to the member indicated by the method name.\n\n``` php\nUserType::SuperAdministrator()-\u003eisModerator(); // -\u003e false\nUserType::SuperAdministrator()-\u003eisSuperAdministrator(); // -\u003e true\nUserType::SuperAdministrator()-\u003eisStudent(); // -\u003e throws Eloquent\\Enumeration\\Exception\\UndefinedMemberException\n```\n\n### static randomMember(): static\n\nReturns a random member from the enum. Useful for factories.\n\n``` php\nUserType::randomMember(); // Returns Administrator(), Moderator(), Subscriber() or SuperAdministrator()\n```\n\n### static defaultMember(): static\n\nReturns the default member for the enum. This function defaults to the first member of the enum when not overridden.\n\n``` php\nUserType::defaultMember(); // Returns Administrator()\n```\n\n### static membersByBlacklist(?array): array\n\nReturns all members except the ones given.\n\n``` php\nUserType::membersByBlacklist([UserType::Moderator()]); // Returns Administrator(), Subscriber() and SuperAdministrator()\n```\n\n### static toSelectArray(?array): array\n\nReturns the enum for use in a select as value =\u003e key. It is also possible to set an optional blacklist-parameter to filter the returned values.\n\n``` php\nUserType::toSelectArray(); // Returns [0 =\u003e 'Administrator', 1 =\u003e 'Moderator', 2 =\u003e 'Subscriber', 3 =\u003e 'SuperAdministrator']\n```\n\n### toLocalizedSelectArray(?array): array\n\nReturns the enum for use in a select as value =\u003e localizedValue, where localizedValue is localized using `-\u003elocalized()`.\nLike `toSelectArray` it is possible to set an optional blacklist-parameter to filter the returned values.\n\n``` php\nUserType::toLocalizedSelectArray(); // Returns [0 =\u003e 'Administrator', 1 =\u003e 'Moderator', 2 =\u003e 'Subscriber', 3 =\u003e 'Super Administrator']\n```\n\n## Validation\n\n### Array Validation\n\nYou may validate that a value passed to a controller is a valid value for a given enum by using the `EnumerationValue` rule, for easier handling there are helper methods for creating the rule: `Enumeration::makeRule()`, `Enumeration::makeRuleWithWhitelist($whitelist)` and `Enumeration::makeRuleWithBlacklist($blacklist)`.\n\n``` php\npublic function store(Request $request)\n{\n    $this-\u003evalidate($request, [\n        'user_type' =\u003e [\n            'required',\n            UserType::makeRule(), // Allows all enumeration values\n        ],\n    ]);\n}\n```\n\n``` php\npublic function store(Request $request)\n{\n    $this-\u003evalidate($request, [\n        'user_type' =\u003e [\n            'required',\n            UserType::makeRuleWithWhitelist([UserType::Moderator(), UserType::Subscriber()]), // allows only the values `1` and `2`\n        ],\n    ]);\n}\n```\n\n``` php\npublic function store(Request $request)\n{\n    $this-\u003evalidate($request, [\n        'user_type' =\u003e [\n            'required',\n            UserType::makeRuleWithBlacklist([UserType::SuperAdministrator(), UserType::Administrator()]), // allows all values but the values `0` and `3`\n        ],\n    ]);\n}\n```\n\n## Localization\n\nYou can translate the strings returned by the `localized` methods using Laravel's built in [localization](https://laravel.com/docs/5.6/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 Danish.\n\n```php\n// resources/lang/en/enums.php\n\u003c?php\n\nuse App\\Enums\\UserType;\n\nreturn [\n\n    UserType::class =\u003e [\n        UserType::Moderator =\u003e 'Moderator',\n    ],\n\n];\n```\n\n```php\n// resources/lang/da/enums.php\n\u003c?php\nuse App\\Enums\\UserType;\n\nreturn [\n\n    UserType::class =\u003e [\n        UserType::Moderator =\u003e 'studievært',\n    ],\n\n];\n```\n\n## Custom Cast\n\nYou can use the `Enum` custom cast to enable automatic casting of properties to enums. When used, it will set the property to the default members value when set to an invalid value, same goes when the initial value is invalid when getting it, it will return the default member.\n\n```php\n\u003c?php\n\nnamespace App\\Models;\n\nuse App\\Enums\\UserType;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Sourceboat\\Enumeration\\Casts\\Enum;\n\nclass User extends Model\n{\n    protected $casts = [\n        'type' =\u003e Enums::class . ':' . UserType::class,\n    ];\n}\n```\n\nBy default the custom cast treats the property as nullable, meaning that the property can be set to null and also return it, instead of an enum member, this can the disabled on an per property basis:\n\n```php\n\u003c?php\n\nnamespace App\\Models;\n\nuse App\\Enums\\UserType;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Sourceboat\\Enumeration\\Casts\\Enum;\n\nclass User extends Model\n{\n    protected $casts = [\n        'type' =\u003e Enums::class . ':' . UserType::class . ',0', // appending the 0 means it is not nullable,\n    ];                                                         // this seems counter intuitive, but thats the way it is recognized as `false`,\n}                                                              // as `false` is somehow evaluated as `true`.\n```\n\nIf the casted attribute is not set to be nullable and/or has a value not represented by the enum, you will get the default member of the enum when accessing the attribute.\n\n```php\n// For example when the value has been changed manually in the database. Let's say the type is `10`.\n$type = $user-\u003etype\n\n// Then the following will be the case:\n\necho $type === UserType::defaultMember(); // \"true\"\necho $type-\u003evalue; // \"0\"\n```\n\nSince Laravel 7.5 and version 2.1 of this package it is also possible to use the enum itself as cast type hint, but beware that `null` is always an allowed value.\n\n```php\n\u003c?php\n\nnamespace App\\Models;\n\nuse App\\Enums\\UserType;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model\n{\n    protected $casts = [\n        'type' =\u003e UserType::class, \n    ];\n}\n```\n\n## Weighted Enums\n\nIt is Possible to define weights for enum members. the standard way is to define the weights a config file and them implement the `Weighted`-interface with the `IsWeighted`-trait and define the path to your config. The weights can be defined as integer or float values.\n\n``` php\n// The Enum\n\u003c?php\n\nnamespace App\\Enums;\n\nuse Sourceboat\\Enumeration\\Enumeration;\nuse Sourceboat\\Enumeration\\Enums\\Interfaces\\Weighted;\nuse Sourceboat\\Enumeration\\Enums\\Traits\\IsWeighted;\n\n/**\n * @method static \\App\\Enums\\UserType Administrator() // These are only for autocompletion etc.\n * @method static \\App\\Enums\\UserType Moderator()\n * @method static \\App\\Enums\\UserType Subscriber()\n * @method static \\App\\Enums\\UserType SuperAdministrator()\n */\nfinal class UserType extends Enumeration implements Weighted\n{\n    use IsWeighted;\n\n    const Administrator = 0;\n    const Moderator = 1;\n    const Subscriber = 2;\n    const SuperAdministrator = 3;\n}\n```\n\nFor further customization the `Weighted::weight(): int|float`-method can be overridden to use your own way of defining the weights.\n\nThe following methods for comparing weighted enum members are available:\n\n* `Weighted::isGreaterThan(Weighted): bool`\n* `Weighted::isGreaterThanOrEuqalTo(Weighted): bool`\n* `Weighted::isEuqalTo(Weighted): bool`\n* `Weighted::isLessThanOrEqualTo(Weighted): bool`\n* `Weighted::isLessThan(Weighted): bool`\n\nThe following methods for filtering the enum are available:\n\n* `Weighted::getMembersGreaterThanThis(): array\u003cWeighted\u003e`\n* `Weighted::getMembersGreaterThanOrEqualToThis(): array\u003cWeighted\u003e`\n* `Weighted::getMembersEqualToThis(): array\u003cWeighted\u003e`\n* `Weighted::getMembersLessThanOrEqualToThis(): array\u003cWeighted\u003e`\n* `Weighted::getMembersLessThanThis(): array\u003cWeighted\u003e`\n* `static Weighted::getMembersGreaterThan(Weighted): array\u003cWeighted\u003e`\n* `static Weighted::getMembersGreaterThanOrEqualTo(Weighted): array\u003cWeighted\u003e`\n* `static Weighted::getMembersEqualTo(Weighted): array\u003cWeighted\u003e`\n* `static Weighted::getMembersLessThanOrEqualTo(Weighted): array\u003cWeighted\u003e`\n* `static Weighted::getMembersLessThan(Weighted): array\u003cWeighted\u003e`\n* `static Weighted::getMembersBetween(Weighted $lowerMember, Weighted $higherMember): array\u003cWeighted\u003e`\n* `static Weighted::getMembersBetweenOrEqualTo(Weighted $lowerMember, Weighted $higherMember): array\u003cWeighted\u003e`\n\n### Model-trait `HasWeightedEnumScopes`\n\nWith the model trait `HasWeightedEnumsScopes` you can easily search for models with enum values greater than one or between two other enum value, even with string values.\n\nAvailable scopes:\n\n* `whereGreaterThanEnum(string $attribute, Weighted $member)`\n* `whereGreaterThanOrEqualToEnum(string $attribute, Weighted $member)`\n* `whereEqualToEnum(string $attribute, Weighted $member)`\n* `whereLessThanOrEqualToEnum(string $attribute, Weighted $member)`\n* `whereLessThanEnum(string $attribute, Weighted $member)`\n* `whereBetweenEnum(string $attribute, Weighted $lowerMember, Weighted $higherMember)`\n* `whereBetweenOrEqualEnum(string $attribute, Weighted $lowerMember, Weighted $higherMember)`\n\n\n## Configurable Enums\n\nIt is possible to define config values for enums and access them without defining the whole path, but a logical part of it.\nThe default path for the configuration is: `enums.\u003cenum class\u003e.\u003cgiven key\u003e.\u003cenum value\u003e`\n\nFor example:\n\n``` php\n// The Enum\n\u003c?php\n\nnamespace App\\Enums;\n\nuse Sourceboat\\Enumeration\\Enumeration;\nuse Sourceboat\\Enumeration\\Enums\\Interfaces\\Configurable;\nuse Sourceboat\\Enumeration\\Enums\\Traits\\IsConfigurable;\n\n/**\n * @method static \\App\\Enums\\UserType Administrator()\n * @method static \\App\\Enums\\UserType Moderator()\n * @method static \\App\\Enums\\UserType Subscriber()\n * @method static \\App\\Enums\\UserType SuperAdministrator()\n */\nfinal class UserType extends Enumeration implements Configurable\n{\n    use IsConfigurable;\n\n    const Administrator = 0;\n    const Moderator = 1;\n    const Subscriber = 2;\n    const SuperAdministrator = 3;\n}\n```\n\n``` php\n// enums.php\n\u003c?php\nuse App\\Enums\\UserType;\n\nreturn [\n    UserType::class =\u003e [\n        'permissions' =\u003e [\n            UserType::Administrator =\u003e [\n                'user.foreign.edit',\n                'user.foreign.delete',\n            ],\n            UserType::Subscriber =\u003e [\n                'user.self.edit',\n                'user.self.delete',\n            ],\n        ]\n    ]\n]\n```\n\nthen you can access these values by:\n\n``` php \nUserType::Subscriber()-\u003econfig('permissions'); // which return the given array.\nUserType::Moderator()-\u003econfig('permissions', ['thread.foreign.archive']); // you can also define a default value.\n```\n\n\n## License information\n\nMuch of the functionality in this Package is inspired by [bensampo/laravel-enum](https://github.com/bensampo/laravel-enum) and some code has been taken from it and modified, for example the `MakeEnumCommand.php`, the `EnumServiceProvider.php` and this readme. Some code has been copied from [eloquent/enumeration](https://github.com/eloquent/enumeration), as at first this package build upon it, but due to depending only on a fraction of functionality we concluded it would be better to internalize the code that we used.\n\n- [bensampo/laravel-enum](https://github.com/bensampo/laravel-enum) is licensed under MIT\n- [eloquent/enumeration](https://github.com/eloquent/enumeration) is licensed under MIT\n- [laravel/framework](https://github.com/laravel/framework) is licensed under MIT\n\nThis package is also licensed under the MIT license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsourceboat%2Flaravel-enumeration","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsourceboat%2Flaravel-enumeration","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsourceboat%2Flaravel-enumeration/lists"}