mindtwo / native-enum
Package for using native php enums.
Requires
- php: >=8.2
- illuminate/collections: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0|dev-master
- illuminate/contracts: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
- illuminate/support: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
- illuminate/translation: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
Requires (Dev)
- laravel/pint: ^1.17
- phpunit/phpunit: ^9.5.10
- squizlabs/php_codesniffer: ^3.6.2|^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
mindtwo/native-enum makes PHP's native enums convenient to use in Laravel. Add the BaseEnum trait to a backed enum and it gains helper methods, validation rules, Eloquent casts, localized labels and a Blade component that hands its cases to JavaScript.
Inspired by BenSampo/laravel-enum, this package builds on PHP's native enum classes instead of constant classes. Everyone is welcome to contribute.
Contents
- Requirements
- Installation
- Quick start
- Good to know
- Documentation
- Change log
- Testing
- Contributing
- Security
- Credits
- License
Requirements
- PHP 8.2 or higher
- Laravel 8 or higher
Installation
composer require mindtwo/native-enum
The service provider is registered through Laravel's package discovery, so there is nothing else to set up. Stubs, validation translations and the config file can be published when you need them, see Get started.
Quick start
Create an enum
php artisan make:enum UserRole
This creates App\Enums\UserRole. Add --localized for an enum with translated labels. You can also write the enum by hand. All it needs is a backing type and the BaseEnum trait:
namespace App\Enums; use mindtwo\NativeEnum\BaseEnum; enum UserRole: int { use BaseEnum; case ADMIN = 10; case CUSTOMER = 50; }
More: Creating enums covers namespaces and custom stubs.
Use the helpers
UserRole::getValues(); // [10, 50] UserRole::getNames(); // ['ADMIN', 'CUSTOMER'] UserRole::asArray(); // [10 => 'ADMIN', 50 => 'CUSTOMER'] UserRole::asSelectArray(); // [10 => 'ADMIN', 50 => 'CUSTOMER'], value => label, sorted by label UserRole::getInstance(10); // UserRole::ADMIN UserRole::getName(10); // 'ADMIN' UserRole::getValue('ADMIN'); // 10 UserRole::ADMIN(); // 10 UserRole::hasValue(10); // true UserRole::hasName('ADMIN'); // true
More: Helper methods lists every method with its return value.
Validate input
use mindtwo\NativeEnum\Rules\EnumName; use mindtwo\NativeEnum\Rules\EnumValue; $request->validate([ 'role' => ['required', new EnumValue(UserRole::class, false)], // 10 or "10" 'sort' => ['required', new EnumName(UserRole::class)], // "ADMIN" ]);
EnumValue is strict by default, so the string "10" fails for an int-backed enum. Pass false as shown for form and query-string input, which always arrives as strings. A third rule, Enum, checks for a case instance.
More: Validation covers the string syntax and error messages.
Cast model attributes
The enum has to implement Laravel's Castable contract. The trait already provides the castUsing() method the contract asks for:
use Illuminate\Contracts\Database\Eloquent\Castable; use mindtwo\NativeEnum\BaseEnum; enum UserRole: int implements Castable { use BaseEnum; case ADMIN = 10; case CUSTOMER = 50; }
class User extends Model { protected $casts = [ 'role' => UserRole::class, ]; }
| Cast | Column content | Attribute value |
|---|---|---|
UserRole::class |
10 |
UserRole::ADMIN |
UserRole::class.':nullable' |
10 or NULL |
UserRole::ADMIN or null |
UserRole::class.':collection' |
[10,50] (JSON) |
array of cases |
UserRole::class.':collection,comma' |
10,50 (text) |
array of cases |
More: Eloquent casts covers column types, modifiers and caveats.
Localize labels
Implement LocalizedEnum and put the labels into lang/{locale}/enums.php:
use mindtwo\NativeEnum\BaseEnum; use mindtwo\NativeEnum\Contracts\LocalizedEnum; enum UserRole: int implements LocalizedEnum { use BaseEnum; case ADMIN = 10; case CUSTOMER = 50; }
// lang/en/enums.php return [ \App\Enums\UserRole::class => [ 'ADMIN' => 'Administrator', 'CUSTOMER' => 'Customer', ], ];
UserRole::ADMIN->name(); // 'Administrator' UserRole::ADMIN->name; // 'ADMIN' UserRole::asSelectArray(); // [10 => 'Administrator', 50 => 'Customer']
More: Localization covers fallbacks and custom translation keys.
Livewire and JavaScript
- Livewire: enums can be typed public properties on a component. See Livewire.
- JavaScript:
<x-m2-enums::serve />exposes the enums listed inconfig/enums.phpaswindow.m2_ServedEnums. See Serving enums to JavaScript.
Good to know
- Lookups compare strictly.
UserRole::getInstance('10')does not match the int value10, and neither does assigning'10'to a cast attribute. Convert request input first, for exampleUserRole::from((int) $request->input('role')). - Unknown values throw.
getInstance(),getName()andgetValue()throwIlluminate\Support\ItemNotFoundExceptionwhen nothing matches. Check withhasValue()orhasName()if the input has not been validated. - Casts need
Castable. Without it,'role' => UserRole::classfalls back to Laravel's own enum cast, and the:nullableand:collectionmodifiers fail. - Random helpers are not secure.
getRandomValue(),getRandomName()andgetRandomInstance()usearray_rand(). Don't use them for tokens or IDs.
Documentation
| Page | Covers |
|---|---|
| Get started | Requirements, installation, publishable assets, your first enum |
| Creating enums | make:enum, namespaces, custom stubs, writing an enum by hand |
| Helper methods | Every method BaseEnum adds, with return values |
| Validation | EnumValue, EnumName, Enum, string syntax, error messages |
| Eloquent casts | Single values, :nullable, :collection, :collection,comma |
| Localization | LocalizedEnum, lang files, translated labels |
| Livewire | Enum properties on components |
| Serving enums to JavaScript | <x-m2-enums::serve /> and window.m2_ServedEnums |
Change log
Please see CHANGELOG for more information on what has changed recently.
Testing
composer test
The test suite is plain PHPUnit and does not need a booted Laravel application.
Contributing
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
Security
If you discover any security related issues, please email info@mindtwo.de instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
