PHPackages                             weboccult/laravel-translatable - 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. weboccult/laravel-translatable

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

weboccult/laravel-translatable
==============================

A Laravel package for easy model translations using morph relationships. Supports multiple languages, caching, validation, and automatic translation loading.

v1.0.0(11mo ago)02MITPHPPHP ^8.0

Since Jun 1Pushed 11mo agoCompare

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

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

Laravel Translatable
====================

[](#laravel-translatable)

A Laravel package for easy model translations using morph relationships. This package allows you to add multilingual support to your Laravel models using a simple trait.

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

[](#installation)

You can install the package via composer:

```
composer require weboccult/laravel-translatable
```

After installing the package, publish the configuration and migration files:

```
php artisan vendor:publish --provider="WebOccult\LaravelTranslatable\TranslatableServiceProvider"
```

Then run the migrations:

```
php artisan migrate
```

Basic Setup
-----------

[](#basic-setup)

1. Add the `HasTranslations` trait to your model and specify translatable attributes:

```
use WebOccult\LaravelTranslatable\Traits\HasTranslations;

class Department extends Model
{
    use HasTranslations;

    protected $fillable = [
        'code'  // non-translatable field
    ];

    // Define which attributes can be translated
    protected $translatable = [
        'name',
        'description',
        'address'
    ];
}
```

Usage Examples
--------------

[](#usage-examples)

### 1. Creating and Setting Translations

[](#1-creating-and-setting-translations)

```
// Create a new department
$department = Department::create([
    'code' => 'IT-001'
]);

// Method 1: Set translations one by one
$department->setTranslation('name', 'Information Technology', 'en');
$department->setTranslation('name', 'Technologies de l\'information', 'fr');
$department->setTranslation('name', 'Tecnología de la Información', 'es');

// Method 2: Set multiple translations at once
$department->updateTranslations([
    'name' => [
        'en' => 'Information Technology',
        'fr' => 'Technologies de l\'information',
        'es' => 'Tecnología de la Información'
    ],
    'description' => [
        'en' => 'Main IT Department',
        'fr' => 'Département principal des TI',
        'es' => 'Departamento Principal de TI'
    ]
]);

// Method 3: Set multiple fields for same locale
$department->setTranslation(
    ['name', 'description'],
    ['IT Department', 'Handles all IT operations'],
    'en'
);
```

### 2. Retrieving Translations

[](#2-retrieving-translations)

```
// Method 1: Get single translation
$name = $department->getTranslation('name', 'en');
// Output: "Information Technology"

// Method 2: Get all translations for an attribute
$allNames = $department->getAllTranslations('name');
// Output:
// [
//     'en' => 'Information Technology',
//     'fr' => 'Technologies de l\'information',
//     'es' => 'Tecnología de la Información'
// ]

// Method 3: Load with translations for current locale
$departments = Department::withTranslations()->get();
foreach ($departments as $dept) {
    echo $dept->getTranslation('name'); // Uses current locale
}

// Method 4: Load with all translations
$department = Department::with('translations')->find(1);
$translations = $department->translations->groupBy('locale');
// Output:
// [
//     'en' => [
//         ['attribute' => 'name', 'value' => 'Information Technology'],
//         ['attribute' => 'description', 'value' => 'Main IT Department']
//     ],
//     'fr' => [
//         ['attribute' => 'name', 'value' => 'Technologies de l\'information'],
//         ['attribute' => 'description', 'value' => 'Département principal des TI']
//     ]
// ]
```

### 3. Querying with Translations

[](#3-querying-with-translations)

```
// Load models with translations for specific locale
$departments = Department::query()
    ->with(['translations' => function($query) {
        $query->where('locale', 'en')
              ->whereIn('attribute', ['name', 'description']);
    }])
    ->get();

// Format for API response
$formatted = $departments->map(function ($department) {
    return [
        'id' => $department->id,
        'code' => $department->code,
        'name' => $department->getTranslation('name', 'en'),
        'description' => $department->getTranslation('description', 'en')
    ];
});
// Output:
// [
//     {
//         "id": 1,
//         "code": "IT-001",
//         "name": "Information Technology",
//         "description": "Main IT Department"
//     }
// ]
```

### 4. Practical Examples

[](#4-practical-examples)

#### Example 1: Controller with Translation Handling

[](#example-1-controller-with-translation-handling)

```
class DepartmentController extends Controller
{
    public function store(Request $request)
    {
        $department = Department::create([
            'code' => $request->code
        ]);

        // Handle translations from form
        // Input format:
        // translations = [
        //     'name' => [
        //         'en' => 'English Name',
        //         'fr' => 'French Name'
        //     ],
        //     'description' => [
        //         'en' => 'English Description',
        //         'fr' => 'French Description'
        //     ]
        // ]
        $department->updateTranslations($request->translations);

        return response()->json([
            'department' => $department,
            'translations' => $department->translations
        ]);
    }

    public function index()
    {
        // Get departments with translations for current locale
        $departments = Department::withTranslations()
            ->get()
            ->map(function ($department) {
                return [
                    'id' => $department->id,
                    'code' => $department->code,
                    'name' => $department->getTranslation('name'),
                    'description' => $department->getTranslation('description')
                ];
            });

        return view('departments.index', compact('departments'));
    }
}
```

#### Example 2: Blade View Usage

[](#example-2-blade-view-usage)

```

@foreach($departments as $department)

        {{ $department->getTranslation('name') }}
        {{ $department->getTranslation('description') }}

            @foreach($department->getAllTranslations('name') as $locale => $name)

                    {{ $locale }}: {{ $name }}

            @endforeach

@endforeach
```

#### Example 3: API Resource

[](#example-3-api-resource)

```
class DepartmentResource extends JsonResource
{
    public function toArray($request)
    {
        $locale = $request->get('locale', app()->getLocale());

        return [
            'id' => $this->id,
            'code' => $this->code,
            'translations' => [
                'name' => $this->getAllTranslations('name'),
                'description' => $this->getAllTranslations('description')
            ],
            'current_locale' => [
                'name' => $this->getTranslation('name', $locale),
                'description' => $this->getTranslation('description', $locale)
            ]
        ];
    }
}

// Output:
// {
//     "id": 1,
//     "code": "IT-001",
//     "translations": {
//         "name": {
//             "en": "Information Technology",
//             "fr": "Technologies de l'information",
//             "es": "Tecnología de la Información"
//         },
//         "description": {
//             "en": "Main IT Department",
//             "fr": "Département principal des TI",
//             "es": "Departamento Principal de TI"
//         }
//     },
//     "current_locale": {
//         "name": "Information Technology",
//         "description": "Main IT Department"
//     }
// }
```

Features
--------

[](#features)

- Easy integration with Laravel models
- Support for multiple translatable attributes
- Efficient relationship-based translation loading
- Flexible query building for translations
- Support for multiple languages
- Bulk translation operations
- Automatic fallback to model attributes

Configuration
-------------

[](#configuration)

You can configure the package by editing the `config/translatable.php` file:

```
return [
    'default_locale' => 'en',
    'fallback_locale' => 'en',
    'available_locales' => [
        'en' => 'English',
        'fr' => 'French',
        'es' => 'Spanish',
    ],
];
```

License
-------

[](#license)

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

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance51

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

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

343d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7eed518750129879de360b9d7d75948bd11e79941bb0158d5a5f7d7e8e08af8d?d=identicon)[adiechahk](/maintainers/adiechahk)

![](https://www.gravatar.com/avatar/769a876ee1a44df55776296c87dbfb8e3e0f685b0b33f07028badd7647286968?d=identicon)[weboccult](/maintainers/weboccult)

---

Top Contributors

[![naineshr-weboccult](https://avatars.githubusercontent.com/u/86237025?v=4)](https://github.com/naineshr-weboccult "naineshr-weboccult (1 commits)")

---

Tags

laravellocalizationi18ntranslationeloquentmultilingualmorphsmodel-translations

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/weboccult-laravel-translatable/health.svg)

```
[![Health](https://phpackages.com/badges/weboccult-laravel-translatable/health.svg)](https://phpackages.com/packages/weboccult-laravel-translatable)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[richan-fongdasen/laravel-i18n

Simple route and eloquent localization / translation in Laravel

1296.6k](/packages/richan-fongdasen-laravel-i18n)[omaralalwi/lexi-translate

Laravel translation package with morph relationships and caching.

754.3k2](/packages/omaralalwi-lexi-translate)[hpolthof/laravel-translations-db

A database translations implementation for Laravel 5.

545.8k](/packages/hpolthof-laravel-translations-db)

PHPackages © 2026

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