Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Laravel Enum Translatable

Laravel Enum Translatable stats

Downloads
2
Stars
7
Open Issues
0
Forks
0

View on GitHub →

A Laravel package that provides translatable enum functionality with easy-to-use methods for working with enum values and their translations

A Laravel package for translatable enums.

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 allTrans() method
  • ๐ŸŽจ Easy Integration: Simple trait-based implementation
  • ๐Ÿงฉ Modular Support: Optional support for modular Laravel applications

Installation

You can install the package via composer:

composer require osama-98/laravel-enum-translatable

Configuration

Publish the config file with:

php artisan vendor:publish --tag="laravel-enums-config"

This will create a config/laravel-enums.php file with the following structure:

return [
'supported_locales' => [
'en',
// 'ar',
// 'es',
// ...
],
 
/*
| Enable modular support (e.g., nWidart/laravel-modules)
| When enabled, translations will be loaded from module namespaces
*/
'modular_enabled' => false,
 
/*
| Translation namespace resolver class
| You can extend TranslationNamespaceResolver and override the
| resolveModuleNamespace() method to customize how module namespaces are detected
*/
'namespace_resolver' => \Osama\LaravelEnums\TranslationNamespaceResolver::class,
];

Usage

Creating a Translatable Enum

Create an enum that uses the EnumTranslatable trait:

<?php
 
namespace App\Enums\Course;
 
use Osama\LaravelEnums\Concerns\EnumTranslatable;
 
enum CourseStatusEnum: string
{
use EnumTranslatable;
 
case DRAFT = 'draft';
case PENDING = 'pending';
case PUBLISHED = 'published';
}

Setting Up Translation Files

Create translation files in your lang directory. The translation key is automatically generated based on the enum class name.

For CourseStatusEnum, the translation key will be enums.course_statuses (the class name without Enum suffix, converted to snake_case and pluralized).

lang/en/enums.php:

return [
'course_statuses' => [
'draft' => 'Draft',
'pending' => 'Pending',
'published' => 'Published',
],
];

lang/ar/enums.php:

return [
'course_statuses' => [
'draft' => 'ู…ุณูˆุฏุฉ',
'pending' => 'ู‚ูŠุฏ ุงู„ู…ุฑุงุฌุนุฉ',
'published' => 'ู…ู†ุดูˆุฑ',
],
];

Using Enums in Models

You can use translatable enums in your Eloquent models with automatic casting:

<?php
 
namespace App\Models;
 
use App\Enums\Course\CourseStatusEnum;
use Illuminate\Database\Eloquent\Model;
 
class Course extends Model
{
protected $fillable = [
'name',
'status',
// ...
];
 
protected function casts(): array
{
return [
'status' => CourseStatusEnum::class,
];
}
}

Getting Enum Options as Array (with value and name)

Use the toArrayTrans() static method to get all enum options as an array with value and name:

// Returns:
// [
// ['value' => 'draft', 'name' => 'Draft'],
// ['value' => 'pending', 'name' => 'Pending'],
// ['value' => 'published', 'name' => 'Published'],
// ]
$options = CourseStatusEnum::toArrayTrans();
// In a controller
public function getStatusOptions()
{
return response()->json([
'data' => CourseStatusEnum::toArrayTrans()
]);
}

Getting Enum as Object (with value and name)

Use the object() method on an enum instance to get it as an object with value and translated name:

$status = CourseStatusEnum::DRAFT;
 
// Returns: ['value' => 'draft', 'name' => 'Draft']
$statusObject = $status->object();

Using in API Resources

You can use the object() method in your API resources to return enum values with their translations:

<?php
 
namespace App\Http\Resources\V1\Course;
 
use App\Enums\Course\CourseStatusEnum;
use Illuminate\Http\Resources\Json\JsonResource;
 
class CourseResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'status' => $this->whenHas('status', fn (CourseStatusEnum $status) => $status->object()),
// Returns: ['value' => 'draft', 'name' => 'Draft']
];
}
}

Getting Translated Value

Get the translated value for a specific locale:

$status = CourseStatusEnum::DRAFT;
 
// Get translation in current locale
$translated = $status->trans(); // 'Draft' or 'ู…ุณูˆุฏุฉ' depending on locale
 
// Get translation in specific locale
$arabic = $status->trans('ar'); // 'ู…ุณูˆุฏุฉ'
$english = $status->trans('en'); // 'Draft'

Getting All Translations

Get all translations for an enum case across all supported locales:

$status = CourseStatusEnum::DRAFT;
 
// Returns: ['en' => 'Draft', 'ar' => 'ู…ุณูˆุฏุฉ']
$allTranslations = $status->allTrans();

Additional Helper Methods

The package also provides several helper methods from the EnumArrayable trait:

// Get all enum case names
$names = CourseStatusEnum::names(); // ['DRAFT', 'PENDING', 'PUBLISHED']
 
// Get all enum values
$values = CourseStatusEnum::values(); // ['draft', 'pending', 'published']
 
// Get enum as key-value array
$array = CourseStatusEnum::toArray(); // ['draft' => 'DRAFT', 'pending' => 'PENDING', ...]
 
// Get random enum case
$random = CourseStatusEnum::randomCase();
 
// Get random enum value
$randomValue = CourseStatusEnum::randomValue();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

License

The MIT License (MIT). Please see License File for more information.

osama-98 photo

Backend & frontend developer from Amman ๐Ÿš€ | Laravel & VueJS enthusiast ๐Ÿ’ป | MySQL maestro ๐Ÿ˜ | Crafting the web's future, one line of code at a time! ๐ŸŒ

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


Osama 98 Laravel Enum Translatable Related Articles

Translatable Enums image

Translatable Enums

Read article
Honeybadger logo

Honeybadger

Simple developer-focused application monitoring for Laravel. Error tracking, log management, uptime monitoring, status pages, and more!

Honeybadger
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Statamic logo

Statamic

The drop-in ready Laravel CMS youโ€™re been waiting for. Go full-stack or headless, flat file or database โ€“ itโ€™s up to you.

Statamic
Blastup logo

Blastup

Blastup provides social media enhancement services including buying Instagram likes, followers, and views, with features like instant delivery and a variety of packages to suit different needs.

Blastup
Securing Laravel logo

Securing Laravel

The essential security resource for Laravel devs, covering everything you need to keep your apps secure. Sign up to receive weekly security tips and monthly in depth articles, diving deep into security concepts you need to know!

Securing Laravel
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review