mohamedbakr57/localized-enum

A simple and lightweight Laravel package that adds localized labels to native PHP enums using Laravel's translation system. Ideal for multi-language applications.

v1.0.0 2025-07-05 18:16 UTC

README

Latest Version on Packagist
Tests
License: MIT

Localized Enum is a simple, lightweight Laravel package that adds localized labels to native PHP enums using Laravel’s translation system.
Perfect for multilingual applications and API responses with dynamic localization support.

πŸ“š Table of Contents

πŸ§ͺ Usage

Basic Usage

TestStatus::Approved->label(); 
// Output: "Approved by Admin" (if translation exists)

Custom Translation Key

TestStatus::Approved->label('custom.status.approved');
// Output: value from that specific key

Fallback Default

TestStatus::Approved->label('missing.key', 'Approved fallback');
// Output: "Approved fallback" if translation not found

Locale from Request Header

If you're building an API and send locale via headers:

GET /api/user
X-Locale: ar

The trait will use the X-Locale value automatically.

πŸ“ Default header key is X-Locale, but it can be overridden.

Override Header Key

If your app uses a different header, override the method in your enum:

enum TestStatus: string
{
    use HasLabel;

    protected function getLocaleHeaderKey(): string
    {
        return 'Accept-Language';
    }
}

Or override getLabelLocale() entirely for full control.

✨ Features

  • 🏷️ Adds label() method to native PHP Enums
  • 🌐 Fully supports Laravel’s translation system
  • 🧠 Smart fallback resolution (from multiple key patterns)
  • πŸ§ͺ Works great in API responses
  • πŸ”§ Easily override locale detection via request headers
  • πŸ”„ Defaults to config('app.locale') if no locale is sent
  • ⚑ Compatible with flat or nested translation files

πŸ“¦ Installation

composer require mohamedbakr57/localized-enum

πŸ“Œ Example Translation File

// lang/en/enums.php
return [
    'TestStatus.Approved' => 'Approved by Admin',
    'TestStatus.Pending'  => 'Waiting',
    'TestStatus.Rejected' => 'Rejected',
];

Supports both:

  • enums.FQCN.CASE
  • enums.Basename.CASE
  • FQCN.CASE
  • Basename.CASE
  • Or just: 'Approved' => 'Approved Label' for flat key fallback

βœ… Requirements

  • PHP: ^8.1
  • Laravel: ^10.0, ^11.0, ^12.0

πŸ§ͺ Testing

composer test
composer test-coverage

Run Pint for formatting:

composer format

🧰 Development

git clone https://github.com/mohamedbakr57/localized-enum.git
cd localized-enum
composer install
composer test

πŸ“„ License

Licensed under MIT License

πŸ™Œ Credits

Built and maintained by Mohamed Bakr
Stars and PRs are welcome ⭐️