Package

Osama 98 Laravel Enum Translatable

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

Package

osama-98/laravel-enum-translatable

View on GitHub →

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 Laravel Enum Translatable Related Articles

Translatable Enums image

Translatable Enums

Read article
Laravel Enum Package for Generating enum-php Classes image

Laravel Enum Package for Generating enum-php Classes

Read article
How To Add Multilingual Support to Eloquent image

How To Add Multilingual Support to Eloquent

Read article
Enhanced Enum Processing with Laravel's Default Parameter Support image

Enhanced Enum Processing with Laravel's Default Parameter Support

Read article
Laravel Enum Package image

Laravel Enum Package

Read article
Converting Array Values to Enum Instances with Laravel's mapInto Method image

Converting Array Values to Enum Instances with Laravel's mapInto Method

Read article

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm

Let your users buy domains without leaving your app

If your Laravel app gives users a site, a storefront, or a workspace, they’ll eventually want their own domain. The name.com API lets them search, register, and connect one without leaving your product. It’s a clean REST API, so Laravel’s HTTP client is all you need.

Let your users buy domains without leaving your app

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum