laravel-polyglot-model maintained by barisdemirhan
Description
Elegant model translations for Laravel with polymorphic storage and eager loading support
Author
Last update
2026/05/14 18:47
(dev-main)
License
Downloads
38
Tags
Laravel Polyglot Model
Elegant model translations for Laravel with polymorphic storage and eager loading support.
Documentation · Report Bug · Request Feature
✨ Features
- 🚀 Simple API - Intuitive trait-based approach
- 🔄 Polymorphic Storage - Single translations table for all models
- ⚡ Eager Loading - Optimized for performance with relationship loading
- 🎯 Magic Getters - Access translations like regular attributes
- 🔍 Query Scopes - Search across translated fields
- 💾 Caching - Built-in cache support for better performance
- 🎭 Events - Hooks for translation create/update/delete
📋 Requirements
- PHP 8.1+
- Laravel 10.x, 11.x, or 12.x
📦 Installation
composer require barisdemirhan/laravel-polyglot-model
Publish and run migrations:
php artisan vendor:publish --tag="polyglot-model-migrations"
php artisan migrate
Optionally publish the config file:
php artisan vendor:publish --tag="polyglot-model-config"
🚀 Quick Start
1. Add the trait to your model
<?php
namespace App\Models;
use PolyglotModel\Contracts\TranslatableContract;
use PolyglotModel\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Model;
class Post extends Model implements TranslatableContract
{
use HasTranslations;
protected array $translatableFields = [
'title',
'slug',
'content',
];
}
2. Set and get translations
// Create a post
$post = Post::create([
'title' => 'Hello World',
'slug' => 'hello-world',
]);
// Set translations
$post->setTranslate('title', 'tr', 'Merhaba Dünya');
$post->setTranslate('title', 'de', 'Hallo Welt');
// Get translations
$post->getTranslate('title', 'tr'); // "Merhaba Dünya"
// Magic getter (uses current locale)
App::setLocale('tr');
$post->title; // "Merhaba Dünya"
3. Query translations
// Search in translated field
Post::searchTranslatable('title', 'Merhaba', 'tr')->get();
// Get posts with complete translations
Post::hasAllRequiredFieldsForLocaleScope('tr')->get();
🛠️ Available Methods
| Method | Description |
|---|---|
setTranslate($field, $locale, $value) |
Set translation |
getTranslate($field, $locale) |
Get translation |
hasTranslation($field, $locale) |
Check if exists |
getAllTranslations() |
Get all as array |
setPreferredLanguage($locale) |
Set preferred language |
⚙️ Configuration
// config/polyglot-model.php
return [
'source_locale' => 'en',
'fallback_locale' => 'en',
'supported_locales' => ['en', 'tr', 'de', 'es', 'fr'],
'cache' => [
'enabled' => true,
'ttl' => 3600,
],
];
🔧 Artisan Commands
php artisan polyglot:stats
php artisan polyglot:clean-orphaned
🧪 Testing
composer test
📄 License
MIT License. See License File for more information.