astrotomic/laravel-translatable
Laravel package for translatable Eloquent models. Store model translations in the database and automatically fetch/save the correct locale with minimal code. Simplifies retrieving and persisting multilingual attributes across your app.
post_translations), adhering to Laravel’s Eloquent conventions. Avoids JSON serialization pitfalls (e.g., querying, indexing).es_MX) and fallback chains (e.g., de → en), aligning with i18n best practices.$post->translations()->where('locale', 'en')->get();
Post::all()->each->translate('en')), though eager loading translations via withTranslations() is recommended.withTranslations() or loadTranslations().whereHas('translations')) may require raw SQL or custom scopes.Cache::remember).App::setLocale) acceptable, or should it be request-scoped?Post, Product)?fr_CA → fr → en)?null or a default value?PostResource::make($post->translate('en'))).posts, products).Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('author');
$table->timestamps();
});
Schema::create('post_translations', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->string('locale')->index();
$table->string('title');
$table->text('content');
$table->unique(['post_id', 'locale']);
});
use Translatable trait to models.$translatedAttributes and $translationModel (if custom).class Post extends Model {
use \Astrotomic\Translatable\Translatable;
public $translatedAttributes = ['title', 'content'];
protected $translationModel = PostTranslation::class;
}
config/translatable.php:
'locales' => ['en', 'fr', 'es'],
'fallback_locale' => 'en',
'translations_wrapper' => null, // or 'translations' for nested data
getTranslationsArray() or manual scripts.$post->fill([
'author' => 'John',
'translations' => [
'en' => ['title' => 'Hello'],
'fr' => ['title' => 'Bonjour'],
],
]);
Post, Product).Accept-Language headers).withTranslations).locale and foreign keys.dd($post->getTranslationsArray()) to inspect translation data.hasTranslation() for missing locales.DB::enableQueryLog()) to diagnose N+1 issues.$translatedAttributes and locale configuration.locale is unique per model (database constraint).fallback_locale is set in config.(model_id, locale).locale if needed.Cache::remember('post:1:en', ...)).| Failure Scenario | Impact | Mitigation |
|---|---|---|
| Missing translation table | hasTranslation() returns false |
Pre-migrate all models; use translateOrNew. |
| Locale not in config | Fallback fails | Validate locales on startup; use try-catch. |
| Database constraint violation | Save fails | Add unique(['post_id', 'locale']) checks. |
| N+1 queries on list pages |
How can I help you explore Laravel packages today?