Home

Awesome

Lexi Translate

<p align="center"> <a href="https://omaralalwi.github.io/lexi-translate" target="_blank"> <img src="https://raw.githubusercontent.com/omaralalwi/lexi-translate/master/public/images/lexi-translate-banner.jpg" alt="lexi translate banner"> </a> </p>

simplify managing translations for multilingual Eloquent models with power of morph relationships and caching .

Its lightweight design and flexibility make it an excellent choice for applications needing multi-language support with minimal performance overhead.

Table of Contents

Installation

You can install the package via Composer:

composer require omaralalwi/lexi-translate

Publishing Configuration File

php artisan vendor:publish --tag=lexi-translate

update table name (if you need, before migration) or any thing in config file if you need .

Publishing Migration File (optional)

php artisan vendor:publish --tag=lexi-migrations

Migration for translations Table

Run the following command to create the translations table:

php artisan migrate

Usage

Defining LexiTranslatable Models

To use the package, include the LexiTranslatable trait in your Eloquent models, and add translated attributes in $translatableFields array:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Omaralalwi\LexiTranslate\Traits\LexiTranslatable;

class Post extends Model
{
    use LexiTranslatable;

    protected $translatableFields = ['title', 'description'];
}

Update or Create Translations

You can use setTranslations method to create or update bulk translations for a model in a single step:

$post = Post::find(1);
// must same following format
$post->setTranslations([
    'ar' => [
        'name' => 'العنوان باللغة العربية',
        'description' => 'الوصف باللغة العربية',
    ],

    'en' => [
        'name' => 'English language Title',
        'description' => 'description in English language',
    ],
]);

OR You can use setTranslation method to create or update one translation for a model in a single step:

$post->setTranslation('title', 'en', 'English Language Title');
$post->setTranslation('description', 'en', 'English Language description');

$post->setTranslation('title', 'ar', 'عنوان باللغة العربية');
$post->setTranslation('description', 'ar', 'وصف باللغة العربية');

Note you can add translated name and description for Post model even if Post model did not has (name and description) attributes .

Retrieving Translations

Important Note: To get better performance , Do Not Depend on translations relation directly when return translations, because it did not use cache Never. it did not use cache to keep it return MorphMany relation , it Return fresh translations from DB , So you can depend on it to create and update translations .

To retrieve translations, simply use transAttr method :

By default it return default app local, else you can specify local.

// get title and description in default app local
$title = $post->transAttr('title');
$title = $post->transAttr('description');

// or get title and description in specific local
$titleInArabic = $post->transAttr('title', 'ar');
$titleInEnglish = $post->transAttr('title', 'ar');

More Examples

you can find more detail examples in Examples File .

Helper Functions

you can use lexi_locales to get supported locals as array, depend on supported_locales in config file.

Usage in Queries

it is easy to use the scopeSearchByTranslation and scopeFilterByTranslation methods:

search by Translated attribute

$posts = Post::searchByTranslation('title', 'keyword')->get();

Specify Locale

$posts = Post::searchByTranslation('title', 'keyword', 'ar')->get();

Filter Posts by Exact Translated Description

$posts = Post::filterByTranslation('description', 'Specific Translated Text')->get();

Cache Handling

Disable Cache:

by default the cache enabled, you can disable it by make use_cache = false , in config/lexi-translate.php file

Cache Management:

Lexi Translate automatically caches translations to boost performance. Also Cache is cleared automatically when translations are updated or deleted by booted function in Translation model .

Clear Model Cache Manually:

If you need to manually clear the cache, you can do so $model->clearTranslationsCache() for ex :

$post->clearTranslationsCache();

Note:

Please note that the supported_locales setting in the configuration file defines the locales that will be handled by the cache by default. If you add additional locales for translations, make sure to include them in the supported_locales list to ensure proper cache handling. Failing to do so may result in cache issues for locales not added to the list.


Using Middlewares for Locale Management

(this is Optional)

This section is optional , it is additional features to handle language switching for API Or Web , without need to install another package .

LexiTranslate provides built-in middlewares to handle locale switching seamlessly for both web and API requests. These middlewares simplify the process of dynamically setting the application's locale based on user input or request headers.

1 . WebLocalized Middleware

The WebLocalized middleware is designed to handle locale switching for web requests. It determines the locale based on the following order of priority:

Registering the Middleware

// Other middlewares...
'localized.web' => \Omaralalwi\LexiTranslate\Middleware\WebLocalized::class,

Register Middleware in Laravel

Applying the Middleware to Routes

just add locale prefix for all routes that want to apply multilingual for them .

Route::prefix('{locale}')->middleware('localized.web')->group(function () {
     // your routes
});

OR

Route::middleware(['localized.web'])->group(function () {
    Route::get('/{locale}/dashboard', function () {
        return view('dashboard');
    });
});

2. ApiLocalized Middleware

The ApiLocalized middleware is designed for API requests. It sets the application's locale based on the value of a custom header defined in your configuration file (api_locale_header_key). If the header is not provided, it defaults to the application's default locale.

Registering the Middleware

 // Other middlewares...
'localized.api' => \Omaralalwi\LexiTranslate\Middleware\WebLocalized::class,

Applying the Middleware to API Routes

Route::middleware(['localized.api'])->group(function () {
        // your routes
});

Features

Testing

To run the tests for this package:

composer test

Alternative Solutions

If Lexi Translate doesn't fully meet your application's needs, you may also consider these popular alternatives:

Both packages offer robust solutions for managing translations but rely on JSON-based storage. If you require scalable, relational storage with built-in caching and dynamic morph relationships, Lexi Translate is the better choice for large-scale or performance-critical applications.


Changelog

Please see CHANGELOG for more information on recent updates.

Contributing

We welcome contributions! If you'd like to contribute, please check the CONTRIBUTING guide for details.

Contributors

This project exists thanks to all the people who contribute.

Security

If you discover any security-related issues, please email omaralwi2010@gmail.com instead of using the issue tracker.

License

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


Helpful Open Source Packages