{"id":13593923,"url":"https://github.com/spatie/laravel-enum","last_synced_at":"2025-05-14T10:07:33.864Z","repository":{"id":34826835,"uuid":"180570906","full_name":"spatie/laravel-enum","owner":"spatie","description":"Laravel support for spatie/enum","archived":false,"fork":false,"pushed_at":"2025-02-25T15:57:50.000Z","size":446,"stargazers_count":353,"open_issues_count":2,"forks_count":36,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-04-07T15:01:20.370Z","etag":null,"topics":["enum","laravel","php"],"latest_commit_sha":null,"homepage":"https://spatie.be/open-source","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/spatie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","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":"spatie","custom":"https://spatie.be/open-source/support-us"}},"created_at":"2019-04-10T11:52:28.000Z","updated_at":"2025-04-04T04:40:51.000Z","dependencies_parsed_at":"2024-03-22T08:48:07.689Z","dependency_job_id":"f93720aa-e4a0-4694-9990-ef8b95706c7d","html_url":"https://github.com/spatie/laravel-enum","commit_stats":{"total_commits":339,"total_committers":34,"mean_commits":9.970588235294118,"dds":0.415929203539823,"last_synced_commit":"a4715b6bcd2f6e6bfa04d339a2bf295e496e47bf"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-enum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-enum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-enum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spatie%2Flaravel-enum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spatie","download_url":"https://codeload.github.com/spatie/laravel-enum/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248933349,"owners_count":21185460,"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":["enum","laravel","php"],"created_at":"2024-08-01T16:01:26.370Z","updated_at":"2025-04-14T18:03:08.146Z","avatar_url":"https://github.com/spatie.png","language":"PHP","funding_links":["https://github.com/sponsors/spatie","https://spatie.be/open-source/support-us"],"categories":["PHP"],"sub_categories":[],"readme":"\n# Laravel support for spatie/enum\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-enum.svg?style=for-the-badge)](https://packagist.org/packages/spatie/laravel-enum)\n[![License](https://img.shields.io/github/license/spatie/laravel-enum?style=for-the-badge)](https://github.com/spatie/laravel-enum/blob/master/LICENSE.md)\n![Postcardware](https://img.shields.io/badge/Postcardware-%F0%9F%92%8C-197593?style=for-the-badge)\n\n[![Build Status](https://img.shields.io/github/workflow/status/spatie/laravel-enum/run-tests?label=tests\u0026style=flat-square)](https://github.com/spatie/laravel-enum/actions?query=workflow%3Arun-tests)\n[![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-enum.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-enum)\n\nThis package provides extended support for our [spatie/enum](https://github.com/spatie/enum) package in Laravel.\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require spatie/laravel-enum\n```\n\n## Support us\n\n[\u003cimg src=\"https://github-ads.s3.eu-central-1.amazonaws.com/laravel-enum.jpg?t=1\" width=\"419px\" /\u003e](https://spatie.be/github-ad-click/laravel-enum)\n\nWe 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).\n\nWe 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).\n\n## Usage\n\n```php\n// a Laravel specific base class\nuse Spatie\\Enum\\Laravel\\Enum;\n\n/**\n * @method static self DRAFT()\n * @method static self PREVIEW()\n * @method static self PUBLISHED()\n * @method static self ARCHIVED()\n */\nfinal class StatusEnum extends Enum {}\n```\n\n### Model Attribute casting\n\nChances are that if you're working in a Laravel project, you'll want to use enums within your models.\nThis package provides two custom casts and the `\\Spatie\\Enum\\Laravel\\Enum` also implements the `\\Illuminate\\Contracts\\Database\\Eloquent\\Castable` interface.\n\n```php\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass TestModel extends Model\n{\n    protected $casts = [\n        'status' =\u003e StatusEnum::class,\n        'nullable_enum' =\u003e StatusEnum::class.':nullable',\n        'array_of_enums' =\u003e StatusEnum::class.':collection',\n        'nullable_array_of_enums' =\u003e StatusEnum::class.':collection,nullable',\n    ];\n}\n```\n\nBy using the casts the casted attribute will always be an instance of the given enum.\n\n```php\n$model = new TestModel();\n$model-\u003estatus = StatusEnum::DRAFT();\n$model-\u003estatus-\u003eequals(StatusEnum::DRAFT());\n```\n\n### Validation Rule\n\nThis package provides a validation rule to validate your request data against a given enumerable.\n\n```php\nuse Spatie\\Enum\\Laravel\\Rules\\EnumRule;\n\n$rules = [\n    'status' =\u003e new EnumRule(StatusEnum::class),\n];\n```\n\nThis rule validates that the value of `status` is any possible representation of the `StatusEnum`.\n\nBut you can also use the simple string validation rule definition:\n\n```php\n$rules = [\n    'status' =\u003e [\n        'enum:'.StatusEnum::class,\n    ],\n];\n```\n\nIf you want to customize the failed validation messages you can publish the translation file.\n\n```bash\nphp artisan vendor:publish --provider=\"Spatie\\Enum\\Laravel\\EnumServiceProvider\" --tag=\"translation\"\n```\n\nWe pass several replacements to the translation key which you can use.\n\n-   `attribute` - the name of the validated attribute\n-   `value` - the actual value that's validated\n-   `enum` - the full class name of the wanted enumerable\n-   `other` - a comma separated list of all possible values - they are translated via the `enums` array in the translation file\n\n### Request Data Transformation\n\nA common scenario is that you receive an enumerable value as part of your request data.\nTo 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.\n\n#### Request macro\n\nThere is a request macro available which is the base for the other possible ways to cast request data to an enumerable.\n\n```php\n$request-\u003etransformEnums($enumCastRules);\n```\n\nThis is an example definition of all possible request enum castings.\nThere are three predefined keys available as constants on `Spatie\\Enum\\Laravel\\Http\\EnumRequest` to cast enums only in specific request data sets.\nAll other keys will be treated as independent enum casts and are applied to the combined request data set.\n\n```php\nuse Spatie\\Enum\\Laravel\\Http\\EnumRequest;\n\n$enums = [\n    // cast the status key independent of it's data set\n    'status' =\u003e StatusEnum::class,\n    // cast the status only in the request query params\n    EnumRequest::REQUEST_QUERY =\u003e [\n        'status' =\u003e StatusEnum::class,\n    ],\n    // cast the status only in the request post data\n    EnumRequest::REQUEST_REQUEST =\u003e [\n        'status' =\u003e StatusEnum::class,\n    ],\n    // cast the status only in the request route params\n    EnumRequest::REQUEST_ROUTE =\u003e [\n        'status' =\u003e StatusEnum::class,\n    ],\n];\n```\n\nYou can call this macro yourself in every part of your code with access to a request instance.\nMost commonly you will do this in your controller action if you don't want to use one of the other two ways.\n\n#### Form Requests\n\nForm requests are the easiest way to cast the data to an enum.\n\n```php\nuse Illuminate\\Foundation\\Http\\FormRequest;\nuse Spatie\\Enum\\Laravel\\Http\\Requests\\TransformsEnums;\nuse Spatie\\Enum\\Laravel\\Rules\\EnumRule;\n\nclass StatusFormRequest extends FormRequest\n{\n    use TransformsEnums;\n\n    public function rules(): array\n    {\n        return [\n            'status' =\u003e new EnumRule(StatusEnum::class),\n            'properties.level' =\u003e new EnumRule(LevelEnum::class),\n        ];\n    }\n\n    public function enums(): array\n    {\n        return [\n            'status' =\u003e StatusEnum::class,\n            'properties.level' =\u003e LevelEnum::class,\n        ];\n    }\n}\n```\n\nThe 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.\n\n```php\nprotected function passedValidation()\n{\n    $this-\u003etransformEnums($this-\u003eenums());\n\n    // ...\n}\n```\n\n### Route Binding\n\nBeside 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.\n\n#### Implicit Binding\n\nTo use implicit route binding, be sure add `Spatie\\Enum\\Laravel\\Http\\Middleware\\SubstituteBindings` middleware. For example, add it in your `app\\Http\\Kernel.php`:\n\n```php\nprotected $middlewareGroups = [\n    'web' =\u003e [\n        // ...\n        \\Spatie\\Enum\\Laravel\\Http\\Middleware\\SubstituteEnumBindings::class,\n    ],\n];\n```\n\nUse a type-hinted variable name that matches route segment to use implicit route binding.\n\n```php\nRoute::get('/posts/{status}', function (StatusEnum $status) {\n    return $status;\n});\n```\n\n#### Explicit Binding\n\nTo have an explicit binding, there is a `Route::enum()` macro.\nIt's important that your route/group uses the `\\Illuminate\\Routing\\Middleware\\SubstituteBindings` middleware.\nThis middleware is enabled by default for the `web` route group.\n\n```php\nRoute::enum('status', StatusEnum::class);\nRoute::get('/posts/{status}', function (Request $request) {\n    return $request-\u003eroute('status');\n});\n```\n\n### Enum Make Command\n\nWe provide an artisan make command which allows you to quickly create new enumerables.\n\n```bash\nphp artisan make:spatie-enum StatusEnum\n```\n\nYou can use `--method` option to predefine some enum values - you can use them several times.\n\n### Faker Provider\n\nIt'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.\nBecause 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`.\nThe static `register()` method is only a little helper - you can for sure register the provider the default way `$faker-\u003eaddProvider(new FakerEnumProvider)`.\n\nThe faker methods itself are inherited from the base packages [Faker Provider](https://github.com/spatie/enum#faker-provider).\n\n### Livewire\n\nYou can use an enum as a property on a Livewire component like this:\n\n```php\nclass ShowCustomer extends Component\n{\n    public StatusEnum $statusEnum;\n\n    public function mount($id)\n    {\n        $customer = Customer::find($id);\n        $this-\u003estatusEnum = $customer-\u003estatus;\n    }\n\n    public function render()\n    {\n        return view('livewire.customer');\n    }\n}\n```\n\nJust one thing is required to make this work: implement `\\Livewire\\Wireable` on all the enums you’ll be using with Livewire::\n\n```php\nuse Livewire\\Wireable;\n\n/**\n * @method static self pending()\n * @method static self active()\n */\nfinal class StatusEnum implements Wireable\n{}\n```\n\n## Testing\n\n```bash\ncomposer test\ncomposer test-coverage\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.\n\n### Security\n\nIf you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker.\n\n## Credits\n\n-   [Brent Roose](https://github.com/brendt)\n-   [Tom Witkowski](https://github.com/Gummibeer)\n-   [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-enum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspatie%2Flaravel-enum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspatie%2Flaravel-enum/lists"}