PHPackages                             mohamed-ahmed/laravel-polylang - 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. [Localization &amp; i18n](/categories/localization)
4. /
5. mohamed-ahmed/laravel-polylang

ActiveLibrary[Localization &amp; i18n](/categories/localization)

mohamed-ahmed/laravel-polylang
==============================

Flexible polymorphic translation package for Laravel 11+

2.0.1(9mo ago)032MITPHPPHP ^8.2

Since Jul 24Pushed 9mo agoCompare

[ Source](https://github.com/mohamedgcoder/laravel-polylang)[ Packagist](https://packagist.org/packages/mohamed-ahmed/laravel-polylang)[ RSS](/packages/mohamed-ahmed-laravel-polylang/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

Laravel PolyLang
================

[](#laravel-polylang)

Flexible polymorphic translation system for Laravel 11+ — clean, simple, and model-agnostic.

---

🔧 Installation
--------------

[](#-installation)

Require the package via Composer:

```
composer require mohamed-ahmed/laravel-polylang
```

---

⚙️ Publish &amp; Migrate
------------------------

[](#️-publish--migrate)

Publish the config and migration files:

```
php artisan vendor:publish --tag=config
php artisan vendor:publish --tag=migrations
php artisan migrate
```

---

🧩 Usage
-------

[](#-usage)

### ✅ 1. Add the `Translatable` Trait to Your Model

[](#-1-add-the-translatable-trait-to-your-model)

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use MohamedAhmed\LaravelPolyLang\Traits\Translatable;

class Item extends Model
{
    use Translatable;

    protected $fillable = [
        'slug',
        'price',
    ];

    // Translatable fields: name, description
}
```

---

### ✅ 2. Create Controller with Store and Show Methods

[](#-2-create-controller-with-store-and-show-methods)

```
namespace App\Http\Controllers;

use App\Models\Item;
use Illuminate\Http\Request;

class ItemController extends Controller
{
    // 🌐 Create a new item with translations
    public function store(Request $request)
    {
        $validated = $request->validate([
            'slug' => 'required|string|unique:items',
            'price' => 'required|numeric',
            'translations' => 'required|array',
            'translations.*.name' => 'required|string',
            'translations.*.description' => 'required|string',
        ]);

        $item = Item::create([
            'slug' => $validated['slug'],
            'price' => $validated['price'],
        ]);

        foreach ($request->input('translations') as $locale => $fields) {
            foreach ($fields as $field => $value) {
                $item->setTranslation($field, $value, $locale);
            }
        }

        return response()->json(['success' => true, 'id' => $item->id], 201);
    }

    // 🌐 Retrieve item in the requested language
    public function show(Request $request, $id)
    {
        $item = Item::with('translations')->findOrFail($id);
        $locale = app()->getLocale();

        return response()->json([
            'id' => $item->id,
            'slug' => $item->slug,
            'price' => $item->price,
            'translations' => $item->getTranslatedAttributes(['name', 'description'], $locale),
        ]);
    }
}
```

---

### ✅ 3. Define API Routes (`routes/api.php`)

[](#-3-define-api-routes-routesapiphp)

```
use App\Http\Controllers\ItemController;
use MohamedAhmed\LaravelPolyLang\Middleware\SetLocale;

Route::middleware([SetLocale::class])->group(function () {
    Route::post('/items', [ItemController::class, 'store']);
    Route::get('/items/{id}', [ItemController::class, 'show']);
});
```

---

### ✅ 4. Make a Request

[](#-4-make-a-request)

#### ✅ Create an Item

[](#-create-an-item)

**POST** `/api/items`

```
{
  "slug": "laptop-pro",
  "price": 1899.99,
  "translations": {
    "en": {
      "name": "Laptop Pro",
      "description": "High-end performance laptop."
    },
    "ar": {
      "name": "حاسوب برو",
      "description": "حاسوب محمول عالي الأداء."
    }
  }
}
```

#### ✅ Fetch an Item with Language Preference

[](#-fetch-an-item-with-language-preference)

**GET** `/api/items/1`

Add the `Accept-Language` header:

```
Accept-Language: ar

```

**Response:**

```
{
  "id": 1,
  "slug": "laptop-pro",
  "price": 1899.99,
  "translations": {
    "name": "حاسوب برو",
    "description": "حاسوب محمول عالي الأداء."
  }
}
```

If Arabic is missing, it automatically falls back to `config('app.locale')`.

---

🧠 How It Works
--------------

[](#-how-it-works)

- Translations are stored in a single polymorphic table.
- You can add translations for any model without modifying the schema.
- Automatically uses the language from `Accept-Language` header via `SetLocale` middleware.
- Falls back to `config('app.locale')` if the requested translation is missing.

---

📂 Example Migration Output
--------------------------

[](#-example-migration-output)

Creates a `translations` table like:

```
id | translatable_type | translatable_id | locale | field       | value
---|-------------------|-----------------|--------|-------------|---------------------------
1  | App\Models\Item   | 1               | en     | name        | Laptop Pro
2  | App\Models\Item   | 1               | ar     | name        | حاسوب برو
3  | App\Models\Item   | 1               | en     | description | High-end performance laptop.
```

---

📜 License
---------

[](#-license)

MIT License © [Mohamed Ahmed](mailto:mohamedgcoder@gmail.com)

---

🙌 Contributions
---------------

[](#-contributions)

Issues and PRs are welcome! 🎉

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance56

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Unknown

Total

1

Last Release

293d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ac11a764baf2f80aa35d8e8f456dce6a84abcd1d15c2f93dcae98e47ed06bff9?d=identicon)[mgcoder](/maintainers/mgcoder)

---

Top Contributors

[![mohamedgcoder](https://avatars.githubusercontent.com/u/39387545?v=4)](https://github.com/mohamedgcoder "mohamedgcoder (15 commits)")

### Embed Badge

![Health badge](/badges/mohamed-ahmed-laravel-polylang/health.svg)

```
[![Health](https://phpackages.com/badges/mohamed-ahmed-laravel-polylang/health.svg)](https://phpackages.com/packages/mohamed-ahmed-laravel-polylang)
```

###  Alternatives

[barryvdh/laravel-translation-manager

Manage Laravel Translations

1.7k3.6M17](/packages/barryvdh-laravel-translation-manager)[vluzrmos/language-detector

Detect the language for your application using browser preferences, subdomains or route prefixes.

109554.8k3](/packages/vluzrmos-language-detector)[kerigard/laravel-lang-ru

Ru lang for Laravel

2116.8k](/packages/kerigard-laravel-lang-ru)[highsolutions/laravel-translation-manager

Manage Laravel Translations

1518.8k](/packages/highsolutions-laravel-translation-manager)[amendozaaguiar/laraveles-spanish-for-jetstream

Archivos de traducción al español latinoamericano para Laravel con Jetstream (auth, pagination, passwords, validation + todas las cadenas de Jetstream).

1412.1k](/packages/amendozaaguiar-laraveles-spanish-for-jetstream)

PHPackages © 2026

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