PHPackages                             omaralalwi/lexi-translate - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. omaralalwi/lexi-translate

ActiveLibrary[Caching](/categories/caching)

omaralalwi/lexi-translate
=========================

Laravel translation package with morph relationships and caching.

1.0.11(8mo ago)754.3k—8.7%15[1 PRs](https://github.com/omaralalwi/lexi-translate/pulls)2MITPHPPHP ^8.1|^8.2|^8.3

Since Nov 16Pushed 8mo ago3 watchersCompare

[ Source](https://github.com/omaralalwi/lexi-translate)[ Packagist](https://packagist.org/packages/omaralalwi/lexi-translate)[ Docs](https://github.com/omaralalwi/lexi-translate)[ RSS](/packages/omaralalwi-lexi-translate/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (18)Used By (2)

Lexi Translate
==============

[](#lexi-translate)

 [ ![lexi translate banner](https://raw.githubusercontent.com/omaralalwi/lexi-translate/master/public/images/lexi-translate-banner.jpg) ](https://omaralalwi.github.io/lexi-translate)

Easily manage translations for multilingual Eloquent models using 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
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
    - [Defining LexiTranslatable Models](#defining-lexitranslatable-models)
    - [update or Create Translations](#update-or-Create-translations)
    - [Retrieving Translations](#retrieving-translations)
    - [More Examples](#more-examples)
    - [Helper Functions](#helper-functions)
    - [Usage in Queries](#Usage-in-Queries)
    - [Cache Handling](#cache-handling)
    - [Using middlewares](#using-middlewares-for-locale-management)
- [Testing](#testing)
- [Alternative Solutions](#alternative-solutions)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [Features](#features)
- [Security](#security)
- [License](#license)
- [Contributors](#contributors)
- [Helpful Packages](#helpful-open-source-packages)

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require omaralalwi/lexi-translate
```

### Publishing Configuration File

[](#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)

[](#publishing-migration-file-optional)

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

### Migration for `translations` Table

[](#migration-for-translations-table)

Run the following command to create the `translations` table:

```
php artisan migrate
```

Usage
-----

[](#usage)

### Defining LexiTranslatable Models

[](#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

[](#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

[](#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

[](#more-examples)

you can find more detail examples in **[Examples File](examples.md)** .

### Helper Functions

[](#helper-functions)

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

### Usage in Queries

[](#usage-in-queries)

it is easy to use the `scopeSearchByTranslation` and `scopeFilterByTranslation` methods:

#### search by Translated attribute

[](#search-by-translated-attribute)

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

#### Specify Locale

[](#specify-locale)

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

#### Filter Posts by Exact Translated Description

[](#filter-posts-by-exact-translated-description)

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

### Cache Handling

[](#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

[](#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**

[](#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:

- The `locale` route parameter.
- The `locale` query string parameter.
- The current session's locale.
- The `locale` stored in cookies.
- The application's default locale.

#### Registering the Middleware

[](#registering-the-middleware)

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

[Register Middleware in Laravel](https://laravel.com/docs/11.x/middleware#registering-middleware)

#### Applying the Middleware to Routes

[](#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**

[](#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

[](#registering-the-middleware-1)

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

#### Applying the Middleware to API Routes

[](#applying-the-middleware-to-api-routes)

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

---

Features
--------

[](#features)

- **Dynamic Morph Relationships:** Manage translations across different models with ease, thanks to its dynamic morph able relationships.
- **Automatic Caching:** Enjoy enhanced performance as translations are automatically cached and invalidated, ensuring quick access and updates.
- **Fallback Mechanism:** Never worry about missing translations—Lexi Translate falls back to the default language if a translation is not available.
- **Simple, Intuitive API:** A clean and consistent API for adding, retrieving, and managing translations.
- **Eloquent-Friendly:** Seamlessly integrates with Laravel's Eloquent ORM, making it easy to work with translated data while maintaining the power of Laravel’s query builder.
- **Search and Filter:** Scopes for search and filters by translations .
- **Built-in middlewares** to handle locale switching seamlessly for both web and API requests.
- **Feature Tests:** supported with Feature Tests .
- **Customize table name:** in config file you can change `table_name` to any name as you want.

Testing
-------

[](#testing)

To run the tests for this package:

```
composer test
```

---

Alternative Solutions
---------------------

[](#alternative-solutions)

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

- **[Spatie Laravel Translatable](https://github.com/spatie/laravel-translatable):**
    Stores translations in a JSON column within the main table. Best suited for smaller applications with simple multilingual requirements.
- **[Astrotomic Laravel Translatable](https://github.com/Astrotomic/laravel-translatable):**
    Similar to Spatie's package but includes additional features like better locale handling. It’s an excellent choice for lightweight multilingual support.

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
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on recent updates.

Contributing
------------

[](#contributing)

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

### Contributors

[](#contributors)

This project exists thanks to all the people who contribute.

- [Omar alalwi](https://github.com/omaralalwi)

Security
--------

[](#security)

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

License
-------

[](#license)

The MIT License (MIT). Please see the [License File](LICENSE.md) for more information.

---

Contributors ✨
--------------

[](#contributors-)

Thanks to these wonderful people for contributing to this project! 💖

   [ ![Omar Al Alwi](https://avatars.githubusercontent.com/u/25439498?v=4)
 **Omar Al Alwi** ](https://github.com/omaralalwi)
 🏆 Creator   [ ![Hamza Hasan](https://avatars.githubusercontent.com/u/62448602?v=4)
 **Hamza Hasan** ](https://github.com/HamzaHassanM)
 💻 Contributor   [ ![Dawood Bawazir](https://avatars.githubusercontent.com/u/110201810?v=4)
 **Dawood Bawazir** ](https://github.com/DBawazir2002)
 💻 Contributor   [ ![KeithTurkowski](https://avatars.githubusercontent.com/u/1822160?v=4)
 **KeithTurkowski** ](https://github.com/KeithTurkowski)
 💻 Contributor  Want to contribute? Check out the [contributing guidelines](./CONTRIBUTING.md) and submit a pull request! 🚀

---

Helpful Open Source Packages
----------------------------

[](#helpful-open-source-packages)

- [![laravel Taxify](https://raw.githubusercontent.com/omaralalwi/Gpdf/master/public/images/gpdf-banner-bg.jpg) Gpdf ](https://github.com/omaralalwi/Gpdf) Open Source HTML to PDF converter for PHP &amp; Laravel Applications, supports Arabic content out-of-the-box and other languages..
- [![laravel Taxify](https://raw.githubusercontent.com/omaralalwi/laravel-taxify/master/public/images/taxify.jpg) **laravel Taxify** ](https://github.com/omaralalwi/laravel-taxify) Laravel Taxify provides a set of helper functions and classes to simplify tax (VAT) calculations within Laravel applications.
- [![laravel Deployer](https://raw.githubusercontent.com/omaralalwi/laravel-deployer/master/public/images/deployer.jpg) **laravel Deployer** ](https://github.com/omaralalwi/laravel-deployer) Streamlined Deployment for Laravel and Node.js apps, with Zero-Downtime and various environments and branches.
- [![laravel Trash Cleaner](https://raw.githubusercontent.com/omaralalwi/laravel-trash-cleaner/master/public/images/laravel-trash-cleaner.jpg) **laravel Trash Cleaner** ](https://github.com/omaralalwi/laravel-trash-cleaner)clean logs and debug files for debugging packages.
- [![laravel Trash Cleaner](https://raw.githubusercontent.com/omaralalwi/laravel-time-craft/master/public/images/laravel-time-craft.jpg) **laravel Time Craft** ](https://github.com/omaralalwi/laravel-time-craft)simple trait and helper functions that allow you, Effortlessly manage date and time queries in Laravel apps.
- [![Laravel Startkit](https://raw.githubusercontent.com/omaralalwi/laravel-startkit/master/public/screenshots/backend-rtl.png) **Laravel Startkit** ](https://github.com/omaralalwi/laravel-startkit) Laravel Admin Dashboard, Admin Template with Frontend Template, for scalable Laravel projects.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance60

Regular maintenance activity

Popularity39

Limited adoption so far

Community22

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 94.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~26 days

Recently: every ~69 days

Total

12

Last Release

260d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/46733da79a34ff686b036a09af1dcc6d21054aee25a5e029500dc87d3c69ba89?d=identicon)[WatheqAlshowaiter](/maintainers/WatheqAlshowaiter)

![](https://www.gravatar.com/avatar/92882431481b621f6509ff259dd600e327c27fc77adcba4fcc7177659059c9a8?d=identicon)[omaralalwi](/maintainers/omaralalwi)

---

Top Contributors

[![omaralalwi](https://avatars.githubusercontent.com/u/25439498?v=4)](https://github.com/omaralalwi "omaralalwi (49 commits)")[![DBawazir2002](https://avatars.githubusercontent.com/u/110201810?v=4)](https://github.com/DBawazir2002 "DBawazir2002 (1 commits)")[![HamzaHassanM](https://avatars.githubusercontent.com/u/62448602?v=4)](https://github.com/HamzaHassanM "HamzaHassanM (1 commits)")[![KeithTurkowski](https://avatars.githubusercontent.com/u/1822160?v=4)](https://github.com/KeithTurkowski "KeithTurkowski (1 commits)")

---

Tags

eloquent-translationi18nlanguage-selectorlaravel-localizationlaravel-translationslexi-translatelocaleslocalizationmany-languagesmulti-regionmultilanguagemultilingualomaralalwiranslatortext-localizationtranslatetranslated-attributestranslation-managementtranslationsspatielaravellocalizationi18ntranslationstranslatelanguagestranslationmultilingualcachemultilanguagelocalesmorphtranslaravel-localeslaravel-translationsdatabase translationslanguage-switchpolyglotlaravel-multi-languagemulti-regiontranslation-managementdynamic-translationlexi-translatemany-languagesmany-localesmulti-localestext-localizationeloquent-translationtranslation-cachespatie translate

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/omaralalwi-lexi-translate/health.svg)

```
[![Health](https://phpackages.com/badges/omaralalwi-lexi-translate/health.svg)](https://phpackages.com/packages/omaralalwi-lexi-translate)
```

###  Alternatives

[laravel-lang/publisher

Localization publisher for your Laravel application

2167.7M24](/packages/laravel-lang-publisher)[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[laravel-lang/common

Easily connect the necessary language packs to the application

1463.1M22](/packages/laravel-lang-common)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
