Enums are a great addition to PHP and Laravel. They are very helpful with code maintainability and clarity. If you are building multilingual applications, you may need to translate those Enum values as well. This is where the Laravel Enum Translatable package, created by Osama Sadah, comes in.
Main Features
- Translation Support: Automatically translate enum values using Laravel's translation system
- Array Conversion: Convert enums to arrays with value and name for easy API responses
- Object Method: Get enum as an object with value and translated name
- Multiple Locales: Support for multiple locales with the
trans()andallTrans()methods - Easy Integration: Simple trait-based implementation
- Modular Support: Optional support for modular Laravel applications
Example
Ensure you add the EnumTranslatable trait to your Enum class.
namespace App\Enums\Article; use Osama\LaravelEnums\Concerns\EnumTranslatable; enum ArticleStatus: string{ use EnumTranslatable; case DRAFT = 'draft'; case PUBLISHED = 'published'; case REJECTED = 'rejected';}
Now you can create translation files in the lang directory of your Laravel application. The translation key is automatically generated based on the enum class name.
For example, in lang/en/enums.php, you could have:
return [ 'article_statuses' => [ 'draft' => 'Draft', 'published' => 'Published', 'rejected' => 'Rejected', ],];
And in lang/es/enums.php, you could have:
return [ 'article_statuses' => [ 'draft' => 'Borrador', 'published' => 'Publicado', 'rejected' => 'Rechazado', ],];
To get the translated value of an Enum, use the trans() or transAll() method:
$status = ArticleStatus::DRAFT; // Get translation in current locale$translated = $status->trans(); // Get translation in specific locale$english = $status->trans('en'); // Outputs: Draft$spanish = $status->trans('es'); // Outputs: Borrador // or All translations$allTranslations = $status->allTrans(); // Outputs: ['en' => 'Draft', 'es' => 'Borrador']
The package also allows you to automatically cast translatable enums in your Eloquent models:
namespace App\Models; use App\Enums\Article\ArticleStatus;use Illuminate\Database\Eloquent\Model; class Article extends Model{ //... protected function casts(): array { return [ 'status' => ArticleStatus::class, ]; }}
Learn more about this package and view the source code on GitHub.