PHPackages                             hibasabouh/laravel-model-translations - 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. [Database &amp; ORM](/categories/database)
4. /
5. hibasabouh/laravel-model-translations

ActiveLibrary[Database &amp; ORM](/categories/database)

hibasabouh/laravel-model-translations
=====================================

Database-driven model translations for Laravel using separate translation tables.

v1.1.0(1mo ago)02MITPHPPHP ^8.1

Since Feb 19Pushed 2mo agoCompare

[ Source](https://github.com/hibasabouh/laravel-model-translations)[ Packagist](https://packagist.org/packages/hibasabouh/laravel-model-translations)[ Docs](https://github.com/hibasabouh/laravel-model-translations)[ RSS](/packages/hibasabouh-laravel-model-translations/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (10)Versions (3)Used By (0)

Laravel Model Translations
==========================

[](#laravel-model-translations)

[![Latest Version on Packagist](https://camo.githubusercontent.com/726d5b35e8eeca3bf4802cd9fd7f27a132e1e16ff4c863c5106ddce6e6d874c1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f686962617361626f75682f6c61726176656c2d6d6f64656c2d7472616e736c6174696f6e732e737667)](https://packagist.org/packages/hibasabouh/laravel-model-translations)[![Total Downloads](https://camo.githubusercontent.com/cdf7820457763cdccb67d20d8cdad330dbe38f1fe6256a8a4919eb2cecc68852/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686962617361626f75682f6c61726176656c2d6d6f64656c2d7472616e736c6174696f6e732e737667)](https://packagist.org/packages/hibasabouh/laravel-model-translations)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP](https://camo.githubusercontent.com/2bcd22c3d92a101d2d2272998e34fa018468ed602686f16783ec3a4122770215/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f686962617361626f75682f6c61726176656c2d6d6f64656c2d7472616e736c6174696f6e732e737667)](https://packagist.org/packages/hibasabouh/laravel-model-translations)

A clean, database-driven approach to model translations in Laravel. Store translations in separate normalized tables and access them with elegant, locale-aware magic accessors.

Why This Package?
-----------------

[](#why-this-package)

Unlike JSON-based translation approaches, this package:

✅ **Relational structure** — Translations live in proper normalized tables
✅ **Query support** — Filter models by translated content with `whereTranslation()`
✅ **Indexing &amp; constraints** — Add database indexes and unique constraints per locale
✅ **Scalability** — Handles large datasets better than JSON columns
✅ **Clean models** — Keeps base model focused, translations separated

If you prefer structured, relational translation tables over JSON columns, this package is for you.

---

Requirements
------------

[](#requirements)

LaravelPHP10.x^8.111.x^8.212.x^8.2---

Quick Start
-----------

[](#quick-start)

**1. Install**

```
composer require hibasabouh/laravel-model-translations
```

**2. Add the trait &amp; define `$translatable`**

```
use HibaSabouh\ModelTranslations\Traits\HasTranslations;

class Product extends Model
{
    use HasTranslations;

    protected array $translatable = ['name', 'description'];
}
```

**3. Create translation table**

```
Schema::create('product_translations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained()->cascadeOnDelete();
    $table->string('lang', 10);
    $table->string('name');
    $table->text('description')->nullable();
    $table->timestamps();

    $table->unique(['product_id', 'lang']);
});
```

**4. Create &amp; access translations**

```
Product::createWithTranslations([
    'sku' => 'LAPTOP-001',
    'name' => ['en' => 'Laptop', 'fr' => 'Ordinateur'],
]);

app()->setLocale('fr');
echo $product->name; // "Ordinateur"
```

**Done!**

---

Features
--------

[](#features)

- 🌍 **Locale-aware accessors** — `$model->name` automatically returns the current locale's value
- 🔄 **Fallback strategies** — Choose between `null`, app fallback, or first available translation
- 🔍 **Query scopes** — `whereTranslation()`, `whereAnyTranslation()` for filtering by translated content
- 💾 **Transactional CRUD** — All operations wrapped in database transactions
- 🎯 **Convention over configuration** — Auto-resolves translation model names
- ⚡ **Eager loading** — Configurable auto-eager-loading via global scope

---

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

[](#installation)

```
composer require hibasabouh/laravel-model-translations
```

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --tag=translatable-config
```

This creates `config/translatable.php`:

```
return [
    'auto_load' => true,  // Eager load translations globally
    'fallback'  => 'app', // Fallback strategy: null, 'app', or 'first'
];
```

---

Setup Guide
-----------

[](#setup-guide)

### 1. Migration: Create Translation Table

[](#1-migration-create-translation-table)

For each translatable model, create a corresponding `{model}_translations` table:

```
Schema::create('product_translations', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained()->cascadeOnDelete();
    $table->string('lang', 10);
    $table->string('name');
    $table->text('description')->nullable();
    $table->timestamps();

    $table->unique(['product_id', 'lang']); // One translation per locale
    $table->index('lang'); // Optional: speed up locale-specific queries
});
```

### 2. Translation Model

[](#2-translation-model)

Create a translation model in the `Translations` sub-namespace:

```
namespace App\Models\Translations;

use Illuminate\Database\Eloquent\Model;

class ProductTranslation extends Model
{
    protected $fillable = ['product_id', 'lang', 'name', 'description'];
}
```

> **Convention:** A `App\Models\Product` model resolves to `App\Models\Translations\ProductTranslation`.

### 3. Add Trait to Main Model

[](#3-add-trait-to-main-model)

```
namespace App\Models;

use HibaSabouh\ModelTranslations\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasTranslations;

    protected $fillable = ['sku', 'price', 'stock'];

    protected array $translatable = ['name', 'description'];
}
```

---

Usage
-----

[](#usage)

### Creating Models

[](#creating-models)

Pass translatable attributes as arrays keyed by locale:

```
Product::createWithTranslations([
    'sku'   => 'LAPTOP-001',
    'price' => 999,
    'name'  => [
        'en' => 'Gaming Laptop',
        'fr' => 'Ordinateur Portable de Jeu',
        'ar' => 'حاسوب محمول للألعاب',
    ],
    'description' => [
        'en' => 'High-performance laptop for gaming',
        'fr' => 'Ordinateur haute performance pour les jeux',
    ],
]);
```

### Updating Models

[](#updating-models)

```
$product->updateWithTranslations([
    'price' => 899, // Update base attribute
    'name'  => [
        'en' => 'Gaming Laptop Pro', // Update existing
        'de' => 'Gaming-Laptop',      // Add new locale
    ],
]);

// Untouched translations ('fr', 'ar') remain unchanged
```

### Reading Translations

[](#reading-translations)

**Locale-aware accessor:**

```
app()->setLocale('fr');
echo $product->name; // "Ordinateur Portable de Jeu"
```

**All translations at once:**

```
$product->name_translations;
// ['en' => 'Gaming Laptop', 'fr' => 'Ordinateur Portable de Jeu', 'ar' => '...']
```

**Direct relationship access:**

```
$product->translations; // Collection of all ProductTranslation records
$product->translations()->where('lang', 'en')->first();
```

### Querying by Translation

[](#querying-by-translation)

**Current locale (default):**

```
app()->setLocale('en');
Product::whereTranslation('name', 'like', '%Laptop%')->get();
```

**Specific locale:**

```
Product::whereTranslation('name', 'Ordinateur', '=', 'fr')->get();
```

**Any locale:**

```
Product::whereAnyTranslation('name', 'like', '%Laptop%')->get();
```

**Chaining with OR:**

```
Product::where('price', ' 'Laptop']);

// ✅ Valid
Product::createWithTranslations(['name' => ['en' => 'Laptop']]);
```

Throws `InvalidTranslationFormatException` with a clear message:

```
The 'name' attribute must be an array of translations in the format: ['locale' => 'value'].

```

---

Testing
-------

[](#testing)

```
composer test
```

Run tests with coverage:

```
composer test -- --coverage
```

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for release history.

---

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

[](#contributing)

Contributions are welcome! Please:

1. Fork the repo
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

License
-------

[](#license)

The MIT License (MIT). See [LICENSE](LICENSE) for details.

---

Credits
-------

[](#credits)

- **Hiba Sabouh** — [GitHub](https://github.com/hibasabouh)
- All contributors

---

Support
-------

[](#support)

- **Issues:** [GitHub Issues](https://github.com/hibasabouh/laravel-model-translations/issues)
- **Source:** [GitHub Repository](https://github.com/hibasabouh/laravel-model-translations)

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance86

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

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

Every ~32 days

Total

2

Last Release

56d ago

### Community

Maintainers

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

---

Top Contributors

[![hibasabouh](https://avatars.githubusercontent.com/u/75159535?v=4)](https://github.com/hibasabouh "hibasabouh (5 commits)")

---

Tags

laravellocalizationi18ntranslationsmodeleloquent

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/hibasabouh-laravel-model-translations/health.svg)

```
[![Health](https://phpackages.com/badges/hibasabouh-laravel-model-translations/health.svg)](https://phpackages.com/packages/hibasabouh-laravel-model-translations)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[sebastiaanluca/laravel-boolean-dates

Automatically convert Eloquent model boolean attributes to dates (and back).

40111.7k1](/packages/sebastiaanluca-laravel-boolean-dates)

PHPackages © 2026

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