Laravel's built-in localization features can indeed be used with enums, especially with the newer PHP enum support (PHP 8.1+) integrated into Laravel. There are different approaches to combining enums and localization, ranging from using the native PHP enums with custom localization methods to using third-party packages like BenSampo's laravel-enum package that extend enum capabilities with localization support.
Native PHP Enums with Laravel Localization
PHP 8.1 introduced native enums, which can be either "backed enums" (enums with scalar values) or "pure enums" (without values). Laravel 11 supports using these enums extensively in Eloquent models, validation, routing, and also allows seamless integration with localization.
To localize enum values in Laravel, you can create language files where the enum values (or cases) are mapped to their localized strings. For example, suppose you have an enum called `TicketStatus`:
php
namespace App\Enums;
enum TicketStatus: string
{
case Open = 'open';
case InProgress = 'in_progress';
case Resolved = 'resolved';
case Closed = 'closed';
}
You would create localization files, e.g., `resources/lang/en/enums.php`, with content like this:
php
return [
'ticket_status' => [
'open' => 'Open',
'in_progress' => 'In Progress',
'resolved' => 'Resolved',
'closed' => 'Closed',
],
];
Then, define a method in the enum to get the localized label:
php
public function label(): string
{
return __("enums.ticket_status.{$this->value}");
}
Now, anywhere in the application, calling `$ticket->status->label()` will return the translated string based on the application's current locale. This makes it easy to switch languages and display user-friendly enum labels without hardcoding text in your codebase.
Using Larave Enum Package by BenSampo
For more extensive enum implementation with validation, localization, and other utilities, the community package BenSampo/laravel-enum is widely used. This package offers:
- A base Enum class for defining enums with integer or string constants
- Validation rules (`EnumValue` and `EnumKey`) for form request validation
- A built-in localization mechanism tied to Laravel's localization system
For localization, this package instructs you to create language files under `resources/lang/{locale}/enums.php` like:
php
use App\Enums\UserType;
return [
UserType::class => [
UserType::Administrator => 'Administrator',
UserType::SuperAdministrator => 'Super administrator',
],
];
In Spanish localization, for example:
php
use App\Enums\UserType;
return [
UserType::class => [
UserType::Administrator => 'Administrador',
UserType::SuperAdministrator => 'Súper administrador',
],
];
To enable localization, your enum class must implement the `LocalizedEnum` interface:
php
use BenSampo\Enum\Enum;
use BenSampo\Enum\Contracts\LocalizedEnum;
final class UserType extends Enum implements LocalizedEnum
{
const Administrator = 0;
const SuperAdministrator = 1;
}
Once implemented, the `getDescription()` method of the enum will return the localized string from the language files based on the current locale automatically. If a localization key doesn't exist, it falls back to the default description (e.g., the constant name).
Benefits of Using Enums with Localization in Laravel
1. Type safety and clarity: Enums provide a central place to define valid values reducing bugs from invalid hardcoded strings or magic numbers.
2. Easy localization: Enums can be localized using Laravel's translation files, supporting multiple languages dynamically.
3. Cleaner codebase: Instead of scattering string literals across views and controllers, enums centralize the identifiers and link to their translations.
4. Validation integration: Laravel validation rules can directly work with enums to ensure users submit only valid values.
5. Use in Eloquent models: Enums can be cast on model attributes, seamlessly converting stored string or integer values back into enum instances with localized accessors.
6. API responses: Enums can easily expose translated labels in API responses by adding localization helper methods.
Implementing Localization with Native PHP Enums (Step-by-Step Example)
1. Create Enum:**
php
namespace App\Enums;
enum OrderStatus: string
{
case Pending = 'pending';
case Processing = 'processing';
case Completed = 'completed';
case Cancelled = 'cancelled';
public function label(): string
{
return __("enums.order_status.{$this->value}");
}
}
2. Create Localization Files:**
- `resources/lang/en/enums.php`
php
return [
'order_status' => [
'pending' => 'Pending',
'processing' => 'Processing',
'completed' => 'Completed',
'cancelled' => 'Cancelled',
],
];
- `resources/lang/es/enums.php`
php
return [
'order_status' => [
'pending' => 'Pendiente',
'processing' => 'En proceso',
'completed' => 'Completado',
'cancelled' => 'Cancelado',
],
];
3. Using Enum in Eloquent Model:**
php
use App\Enums\OrderStatus;
class Order extends Model
{
protected $casts = [
'status' => OrderStatus::class,
];
}
4. Using the Localized Label:**
php
$order = Order::find(1);
echo $order->status->label(); // Displays localized value depending on app locale
Localized Enum Validation
Laravel provides an `Enum` validation rule which can be used with native enums:
php
use App\Enums\OrderStatus;
use Illuminate\Validation\Rules\Enum;
$request->validate([
'status' => ['required', new Enum(OrderStatus::class)],
]);
This ensures only valid enum cases are accepted.
Handling Multilingual Enums in API Responses
For API responses, the localized label method can be used to return both the enum value and its localized label:
php
return [
'status' => $order->status->value,
'status_label' => $order->status->label(),
];
This technique provides clean, type-safe data with user-friendly labels in the preferred language of the client.
Summary of Key Points on Using Laravel Localization with Enums
- You can use Laravel's native localization system by creating translation files with enum keys and their localized descriptions.
- PHP 8.1 native enums integrate well with Laravel features like model casting and request validation.
- A method returning the translated label using Laravel's `__()` helper is a robust pattern for localization.
- External packages like BenSampo's laravel-enum provide additional support, especially for legacy applications or where integer-based enums are preferred.
- Enum localization eliminates duplicated hardcoded strings and centralizes translations, improving maintainability and internationalization capabilities.
- Validation rules directly supporting enums help ensure data integrity when accepting user input.
- APIs benefit from this approach by returning both raw values and translated labels, enhancing client usability globally.
Laravel's localization combined with enums brings type safety, cleaner code, easier translations, and better validation into a cohesive development experience well suited to modern multi-language applications. This approach fits Laravel's philosophy of expressive, elegant code that facilitates both development and internationalization workflows.
The capabilities continue to evolve with Laravel and PHP versions, making enums and localization a recommended pattern for handling fixed value sets in languages beyond English. This modern tooling approach will keep your application scalable and maintainable in diverse language environments.