- PHP 8.2 or higher
- Laravel 8 or higher
composer require mindtwo/native-enumThe service provider is auto-discovered, so no manual registration is needed.
Nothing has to be published to use the package. Publish an asset only when you want to change it:
| Asset | Tag | Published to | Needed for |
|---|---|---|---|
| Generator stubs | stubs |
stubs/enum.stub, stubs/enum-localized.stub |
Customizing make:enum |
| Validation messages | translations |
lang/vendor/native-enum/{locale}/messages.php |
Changing error messages |
| Config file | none | config/enums.php |
Serving enums to JavaScript |
# One asset
php artisan vendor:publish --provider="mindtwo\NativeEnum\EnumServiceProvider" --tag=stubs
php artisan vendor:publish --provider="mindtwo\NativeEnum\EnumServiceProvider" --tag=translations
# Everything, including config/enums.php
php artisan vendor:publish --provider="mindtwo\NativeEnum\EnumServiceProvider"The config file has no tag of its own, so it is published together with the other assets by the last command.
Generate it:
php artisan make:enum UserRoleOr write it by hand:
namespace App\Enums;
use mindtwo\NativeEnum\BaseEnum;
enum UserRole: int
{
use BaseEnum;
case ADMIN = 10;
case CUSTOMER = 50;
}Then use it:
UserRole::asSelectArray(); // [10 => 'ADMIN', 50 => 'CUSTOMER'], ready for a dropdown
UserRole::getInstance(10); // UserRole::ADMIN
UserRole::ADMIN(); // 10
UserRole::hasName('ADMIN'); // true
new \mindtwo\NativeEnum\Rules\EnumValue(UserRole::class); // validation rule- Creating enums: namespaces, localized enums, custom stubs
- Helper methods: the full method reference
- Validation: validate request input against an enum
- Eloquent casts: store enums on models
- Localization: translated labels
- Livewire and Serving enums to JavaScript: enums in the frontend