A localized enum has a translated label for each case, for example for a <select> or a table column.
-
Implement
LocalizedEnum, or generate the enum withphp artisan make:enum UserRole --localized:namespace App\Enums; use mindtwo\NativeEnum\BaseEnum; use mindtwo\NativeEnum\Contracts\LocalizedEnum; enum UserRole: int implements LocalizedEnum { use BaseEnum; case ADMIN = 10; case CUSTOMER = 50; }
-
Add the labels to
lang/{locale}/enums.php, keyed by the enum class and the case name:// lang/en/enums.php return [ \App\Enums\UserRole::class => [ 'ADMIN' => 'Administrator', 'CUSTOMER' => 'Customer', ], ];
| Call | Returns |
|---|---|
UserRole::ADMIN->name() |
'Administrator' |
UserRole::ADMIN->name |
'ADMIN', PHP's case name, never translated |
UserRole::getLocalizedName('ADMIN') |
'Administrator' |
UserRole::asSelectArray() |
[10 => 'Administrator', 50 => 'Customer'], sorted by label |
UserRole::asServableEnum() |
Each entry's localized_name holds the label |
Labels follow the current application locale.
The case name is returned instead of a label when:
- the enum does not implement
LocalizedEnum, - there is no translation for the case in the current locale or in the application's fallback locale, or
- no translator is available, for example in a unit test without a Laravel application.
By default the key is enums.<fully qualified class name>.<case name>. Define getLocalizationName() on the enum to use a different prefix:
enum UserRole: int implements LocalizedEnum
{
use BaseEnum;
case ADMIN = 10;
case CUSTOMER = 50;
public static function getLocalizationName(): string
{
return 'enums.user_role';
}
}// lang/en/enums.php
return [
'user_role' => [
'ADMIN' => 'Administrator',
'CUSTOMER' => 'Customer',
],
];- Helper methods: all label-related methods
- Serving enums to JavaScript: labels in the frontend