Laravel Packagev12.0.1MIT LicenseAI Ready

Laravel Translatable

Laravel Translatable gives your Eloquent models translated fields, stored the way that fits each model. It supports three storage strategies behind one API: a translations table, a JSON column per field, or a column per field and locale. Reads, writes, scopes, events and fallbacks behave the same under all three, so you can start with one and move a model to another with a command.

AI Ready

Laravel Translatable ships Laravel Boost resources: a guideline loaded in every session and a translatable-development skill loaded when your agent works on translations. Run php artisan boost:install and Claude Code, Cursor, Codex, Copilot or Gemini CLI write correct code for all three strategies. See AI Ready.

Translations Table

One row per model and locale in a translations table, with a real HasMany relation. The default, and the 2.x storage.

JSON Column per Field

Each translated field is one JSON column holding every locale on the model's own row.

Column per Locale

Each field has a column per locale, such as title_en and title_ar, discovered from your table.

One API

The same reads, writes, scopes and events under every strategy, with the same results on every database.

Move Between Strategies

Copy, verify and roll back a model's translations between strategies with journaled, resumable commands.

AI Ready

Laravel Boost guideline and skill included, so php artisan boost:install teaches your coding agent the package.

#The Same Post, Three Ways

The same two translations, as each strategy stores them:

post_translations
1id | post_id | locale | title
21 | 1 | en | Hello
32 | 1 | ar | مرحبا
posts
1id | title
21 | {"en": "Hello", "ar": "مرحبا"}
posts
1id | title_en | title_ar
21 | Hello | مرحبا

And the code is the same for all three:

1$post->setTranslation('title', 'en', 'Hello')->setTranslation('title', 'ar', 'مرحبا')->save();
2 
3$post->getTranslation('title', 'ar'); // "مرحبا"
4Post::whereTranslation('title', 'Hello', 'en')->get();
Quick Tip

Start with the default translations table. It keeps the storage of the 2.x releases, and you can move a model to JSON or columns later with the strategy migration commands, without losing data.

#Installation

Install the package with Composer. Laravel discovers the service provider automatically.

#Requirements

  • PHP 8.2, 8.3, 8.4 or 8.5
  • Laravel 12.0 or newer within 12.x
  • A database supported by Laravel: SQLite, MySQL, MariaDB or PostgreSQL

#Composer Installation

Terminal
composer require pharaonic/laravel-translatable

#Publish Configuration

Publishing the config is optional. Without it, every model uses the table strategy unless it says otherwise.

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

This creates config/translatable.php.

#Publish Stubs

Publish the stubs only if you want to change the files make:translatable generates.

Terminal
php artisan vendor:publish --tag=translatable-stubs

The stubs are copied to stubs/translatable, and the published copies are used instead of the package's.

Publish Tags

--tag=laravel-translatable (or --tag=pharaonic) publishes the config. The stubs are only published with --tag=translatable-stubs.

Installation Complete

You're all set! Run php artisan make:translatable Post -m to create a translatable model with its migrations.

#Configuration

The configuration has one key: the default strategy.

config/translatable.php
1return [
2 // table, json or columns
3 'strategy' => env('TRANSLATABLE_STRATEGY', 'table'),
4];
Key Default Description
strategy table The strategy of every model that has no strategy marker. Read from TRANSLATABLE_STRATEGY.

A model with a marker interface (TableTranslatable, JsonTranslatable or ColumnsTranslatable) always uses that strategy, whatever the configuration says. An invalid value throws InvalidTranslationStrategyException.

#Locales

The package has no locale list of its own. It uses Laravel's:

Laravel setting Used for
app.locale (App::getLocale()) The current locale: $post->title, and every method called without a locale
app.fallback_locale The locale a displayed value falls back to

Change the current locale with App::setLocale('ar'), for example in a middleware. It is read on every access, so the same model shows each request's locale.

Changing the Strategy

Changing strategy, or a model's marker, never moves data. A model that switches strategy reads empty translations until you copy them with the strategy migration commands.

#Basic Usage

Add the Translatable trait to a model and list its translated fields in $translatables.

app/Models/Post.php
1namespace App\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4use Pharaonic\Laravel\Translatable\Translatable;
5 
6class Post extends Model
7{
8 use Translatable;
9 
10 protected $fillable = ['published'];
11 
12 protected $translatables = ['title', 'content'];
13}

With the default table strategy, the translations live in a PostTranslation model and a post_translations table. php artisan make:translatable Post -m creates the model, the translation model and both migrations for you (see Generators).

#Writing Translations

Set one value, several locales of a field, or several fields of several locales, then save the model.

1$post = new Post(['published' => true]);
2 
3$post->setTranslation('title', 'en', 'Hello')
4 ->setTranslation('title', 'ar', 'مرحبا')
5 ->save();
6 
7$post->setTranslations('content', ['en' => 'Body', 'ar' => 'المحتوى'])->save();
8 
9$post->fillTranslations([
10 'en' => ['title' => 'Hello', 'content' => 'Body'],
11 'ar' => ['title' => 'مرحبا', 'content' => 'المحتوى'],
12])->save();

Setting a translated attribute writes the current locale:

1App::setLocale('ar');
2 
3$post->title = 'مرحبا';
4$post->save();

#Reading Translations

$post->title is the value of the current locale, or of the fallback locale when it has none. getTranslation() returns exactly what is stored.

1App::setLocale('fr');
2 
3$post->title; // "Hello" (from the fallback locale, en)
4$post->getTranslation('title', 'ar'); // "مرحبا"
5$post->getTranslation('title', 'fr'); // null
6$post->getTranslation('title', 'fr', true); // "Hello"
7$post->getTranslations('title'); // ['ar' => 'مرحبا', 'en' => 'Hello']

#Querying

Scopes filter and sort by translated values, under every strategy.

1Post::whereTranslation('title', 'Hello', 'en')->get();
2Post::whereTranslationLike('title', '%ello%')->get();
3Post::translated('ar')->orderByTranslation('title', 'asc', 'ar')->get();
Mass Assignment

$fillable is never changed for you. Add title to make the current locale's value fillable, or locale to accept a ['locale' => ['en' => ['title' => '…']]] payload.

#Strategies

Laravel Translatable supports three ways to store translations. Every model picks one, and the rest of the package (reads, writes, scopes, events, fallbacks, generators) works the same for all three.

#Choosing a Strategy

If your model… Use
has many locales, long text, or comes from 2.x table
has a few translated fields and an open-ended list of locales, and you want no extra table json
has a small fixed set of locales, and you filter or sort by translated values with plain indexes columns

Mix them freely: a Post can use a translations table while a Tag uses JSON and a Country uses columns, in the same application.

#How a Model Picks One

Each model uses exactly one strategy:

  1. its marker interface, when it implements one;
  2. otherwise config('translatable.strategy');
  3. otherwise table.

Implementing two markers throws ConflictingTranslationStrategiesException.

Strategy Marker Storage Best for
table TableTranslatable A translation model, one row per model and locale Many locales, long text, the 2.x storage
json JsonTranslatable One JSON column per field: {"en": "Hello", "ar": "مرحبا"} Few fields, any number of locales, no extra table
columns ColumnsTranslatable One column per field and locale: title_en, title_ar A small fixed set of locales, plain indexes

#Table

The 2.x storage. A Post model uses a PostTranslation model in the same namespace, a post_translations table, a post_id foreign key and a locale column, with a real HasMany relation.

app/Models/Post.php
1use Pharaonic\Laravel\Translatable\Contracts\TableTranslatable;
2 
3class Post extends Model implements TableTranslatable
4{
5 use Translatable;
6 
7 protected $translatables = ['title', 'content'];
8}
app/Models/PostTranslation.php
1class PostTranslation extends Model
2{
3 protected $table = 'post_translations';
4 
5 protected $fillable = ['locale', 'post_id', 'title', 'content'];
6}
database/migrations/2020_01_01_000001_create_post_translations_table.php
1Schema::create('post_translations', function (Blueprint $table) {
2 $table->id();
3 $table->unsignedBigInteger('post_id');
4 $table->string('locale', 35);
5 $table->string('title')->nullable();
6 $table->text('content')->nullable();
7 $table->unique(['post_id', 'locale']);
8 $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
9});

The unique index on the foreign key and the locale keeps one row per model and locale, and it is the index every translation query uses. Override the names on the model with getTranslatableModel(), getTranslatableTable() and getTranslatableField().

#JSON

Each translated field is a JSON column with the field's own name.

app/Models/Post.php
1use Pharaonic\Laravel\Translatable\Contracts\JsonTranslatable;
2 
3class Post extends Model implements JsonTranslatable
4{
5 use Translatable;
6 
7 protected $translatables = ['title', 'content'];
8}
database/migrations/2020_01_01_000000_create_posts_table.php
1Schema::create('posts', function (Blueprint $table) {
2 $table->id();
3 $table->json('title')->nullable();
4 $table->json('content')->nullable();
5 $table->timestamps();
6});

The json strategy needs no $casts: the package reads and writes these columns itself, and the value types come from translatable(). Casts you add on them anyway do no harm.

A save locks the row, reads the stored JSON again, and writes back only the locales you changed, so two requests that write different locales both keep their values.

#Columns

Each field has one column per locale, named {field}_{locale}. The locale is lowercased, with - written as _: title_en, title_ar, title_pt_br.

app/Models/Post.php
1use Pharaonic\Laravel\Translatable\Contracts\ColumnsTranslatable;
2 
3class Post extends Model implements ColumnsTranslatable
4{
5 use Translatable;
6 
7 protected $translatables = ['title'];
8}
database/migrations/2020_01_01_000000_create_posts_table.php
1Schema::create('posts', function (Blueprint $table) {
2 $table->id();
3 $table->string('title_en')->nullable();
4 $table->string('title_ar')->nullable();
5 $table->timestamps();
6});

The locales are the columns the table has. Setting a locale without a column throws TranslationSchemaException; add the column with a migration first. Under this strategy, pt-BR and pt_BR are the same locale and read back as pt_br.

Column Names

On a columns-strategy table, any column named like title_xx or title_xxx (a translated field, then two or three letters) is read as a locale of that field. Don't give other columns that shape.

#Field Definitions

$translatables lists untyped fields. To give fields a type or make them required, return them from a translatable() method instead.

app/Models/Product.php
1class Product extends Model implements JsonTranslatable
2{
3 use Translatable;
4 
5 public function translatable(): array
6 {
7 return [
8 'name' => ['type' => 'string', 'required' => true],
9 'description' => ['required' => true],
10 'price' => ['type' => 'float'],
11 'features' => ['type' => 'array'],
12 'released_on' => ['type' => 'date'],
13 'notes' => ['fallback' => false],
14 ];
15 }
16}

A plain list works in the method too: return ['name', 'description'];. When both the method and $translatables exist, the method wins, and they must list the same fields.

#Options

Option Values Description
type string, int, float, bool, array, object, date, datetime, or a custom cast class (Laravel 7+) Values are cast when read and checked when set.
required true / false Required fields decide completeness: hasCompleteTranslation(), missingTranslations(), translationProgress().
fallback true / false false never shows another locale's value for this field.

A typed field only accepts values of its type, so nothing is silently converted: setting '5' or 1.5 on an int field throws InvalidTranslationValueException. null is always accepted.

#Completeness

1$product->hasCompleteTranslation('ar'); // false
2$product->missingTranslations('ar'); // ['description']
3$product->translationProgress('ar'); // 50
4 
5Product::whereTranslationProgress('ar', '>=', 100)->get();

translationProgress() is the percentage of required fields that have a value, and 100 for a model without required fields.

#Rules

  • translations and locales cannot be field names, and neither can the model's key.
  • A translated field cannot have a set mutator (setTitleAttribute). Get accessors still work and receive the displayed value.
  • Storage options (column, strategy, …) are not field options. Storage comes only from the strategy.

Breaking a rule throws InvalidTranslatableDefinitionException the first time the model is used.

#Reading & Writing

Every method takes an optional locale; without one it uses the current locale (App::getLocale()). Locales are validated (letters, digits, - and _, like en, pt-BR or zh-Hant-TW), and a malformed one throws InvalidLocaleException.

#Exact Values and Displayed Values

An exact read returns what is stored for the locale, or null. A displayed read may fall back to app.fallback_locale.

1$post->getTranslation('title', 'fr'); // null: nothing stored in French
2$post->getTranslation('title', 'fr', true); // "Hello": displayed, from the fallback locale
3$post->title; // displayed, in the current locale

resolveTranslation() tells you where a displayed value came from:

1$resolved = $post->resolveTranslation('title', 'fr');
2 
3$resolved->value; // "Hello"
4$resolved->requestedLocale; // "fr"
5$resolved->resolvedLocale; // "en"
6$resolved->isFallback; // true
7$resolved->isMissing; // false

getTranslationOrFail() returns the exact value or throws MissingTranslationException.

#Reading Everything

1$post->getTranslations('title'); // ['ar' => 'مرحبا', 'en' => 'Hello']
2$post->getTranslations(); // ['title' => ['ar' => …, 'en' => …], 'content' => […]]
3$post->getTranslationsForLocale('ar'); // ['title' => 'مرحبا', 'content' => null]
4$post->getTranslatedLocales(); // ['ar', 'en']
5$post->hasTranslation('ar'); // true: any field in Arabic
6$post->hasTranslation('ar', 'content'); // false

#Writing and Removing

Writes are staged on the model and stored by save().

1$post->setTranslation('title', 'ar', 'مرحبا');
2$post->setTranslations('title', ['en' => 'Hello', 'ar' => 'مرحبا']);
3$post->fillTranslations(['en' => ['title' => 'Hello', 'content' => 'Body']]);
4 
5$post->forgetTranslation('title', 'ar'); // removes one value
6$post->forgetTranslations('ar'); // removes every field of the locale
7 
8$post->save();

Setting a field that is not translated throws UnknownTranslatableFieldException. A save() never deletes translations you didn't forget.

#Dirty Tracking

Translated values are not model attributes, so isDirty() and getDirty() don't list them. Use the translation methods:

1$post->setTranslation('title', 'ar', 'أهلا');
2 
3$post->isTranslationDirty(); // true
4$post->isTranslationDirty('title', 'ar'); // true
5$post->getDirtyTranslations(); // ['title' => ['ar' => 'أهلا']]
6 
7$post->save();
8 
9$post->wasTranslationChanged('title'); // true
10$post->getTranslationChanges(); // ['title' => ['ar' => 'أهلا']]

Setting a value equal to the stored one is not a change. refresh() discards unsaved translation changes, and replicate() copies the translations to the replica as unsaved changes.

#translate()

translate() returns one locale's translation. Under the table strategy it is the translation model; under json and columns it is a LocaleTranslation object you can read and write like one.

1$translation = $post->translate('ar');
2$translation->title; // "مرحبا"
3$post->translate(); // the current locale's
4$post->translate('de'); // null: no German value
5 
6$post->translateOrNew('fr')->title = 'Bonjour';
7$post->save(); // stores the French title
8 
9$post->translateOrDefault('fr'); // the French translation, else the fallback locale's, else null
10$post->translateOrFail('de'); // throws NotFoundHttpException (a 404) when missing

A locale counts as translated when at least one field has a value in it. Values set through a translation ($translation->title = …) are stored by the model's save(), in the same transaction, under every strategy.

#Serialization

When the translations are loaded (with withTranslations(), or after a read) or changed, toArray() and JSON include each translated field's displayed value in the current locale. The raw JSON or {field}_{locale} columns are never serialized. Under the table strategy, a loaded translations relation is serialized as a list, like any relation.

#Querying

The scopes give the same results under every strategy, on SQLite, MySQL, MariaDB and PostgreSQL. Field names, locales and operators are validated, and values are always bound.

#Filtering by Value

1Post::whereTranslation('title', 'Hello', 'en')->get();
2Post::whereTranslation('title', 'Hello')->get(); // any locale
3Post::whereTranslation('rank', 3, 'en', 'whereHas', '>=')->get();
4Post::whereTranslation('title', 'Hello', 'en')->orWhereTranslation('title', 'Hi', 'en')->get();
5 
6Post::whereTranslationLike('title', '%laravel%', 'en')->get();
7Post::whereTranslationIn('status', ['draft', 'review'], 'en')->get();
8Post::whereTranslationNotIn('status', ['archived'], 'en')->get();

whereTranslation() keeps its 2.x signature: the fourth argument is whereHas or orWhereHas, and the operator must be =, !=, <>, <, >, <=, >=, like or not like. Without a locale, whereTranslation() and the Like scopes match any locale; the In scopes use the current locale.

#Filtering by Presence

1Post::translated('ar')->get(); // at least one field has an Arabic value
2Post::translated()->get(); // the same, in the current locale
3Post::notTranslated('ar')->get();
4Post::whereHasTranslation('ar', 'content')->get(); // content has an Arabic value
5Post::whereMissingTranslation('ar', 'content')->get();
6Post::whereTranslationProgress('ar', '<', 100)->get(); // required fields still missing in Arabic

#Sorting

1Post::orderByTranslation('title', 'asc', 'ar')->get();
2Post::orderByTranslation('title', 'asc', 'ar', true)->get(); // sort by the fallback value when Arabic is missing
3Post::translatedSorting('ar', 'title', 'desc')->get(); // 2.x: Arabic only, then by key

Records without a value always sort last.

#Eager Loading

Under the table strategy, withTranslations() eager loads the translations relation, optionally only some locales. Under json and columns the values are already on the row.

1Post::withTranslations()->get();
2Post::withTranslations(['en', 'ar'])->get();

Reading a loaded locale needs no query. A locale outside the list is never read as missing: the first read of one loads the model's other translations once. Include the fallback locale in the list when your pages show fallback values.

Indexes

Under the columns strategy, index the {field}_{locale} columns you filter or sort by. Under the table strategy, the unique index on the foreign key and locale already serves the translation queries.

#Saving & Events

#Transactions

save() writes the model and its translations in one transaction on the model's connection. If anything fails, nothing is stored and the changes stay pending on the model, so you can save again.

  • Table: changed rows are updated, new locales inserted, forgotten locales deleted. When another request inserts the same locale at the same moment, the row it created is updated instead of failing on the unique index.
  • JSON: the row is locked and read again, and only the changed locales are written, so concurrent writers of other locales or fields are kept.
  • Columns: only the changed columns are written.

Deadlocks and serialization failures are retried up to three times. Deleting a model (not a soft delete) deletes its translation rows. A save() with no changes writes nothing and doesn't touch updated_at.

#Events

Event Properties Dispatched
Events\TranslationSet model, field, locale, value, previous Once per stored field and locale
Events\TranslationRemoved model, field, locale, previous Once per removed field and locale
Events\TranslationsMigrated model, from, to, migrationId, records When translatable:migrate --apply finishes

The translation events fire after the save's transaction commits; inside your own DB::transaction(), after it commits on Laravel 8.19+. Saving inside Model::withoutEvents() dispatches none.

app/Providers/EventServiceProvider.php
1use Pharaonic\Laravel\Translatable\Events\TranslationSet;
2 
3protected $listen = [
4 TranslationSet::class => [
5 \App\Listeners\ClearPageCache::class,
6 ],
7];

#Custom Fallbacks

Bind your own FallbackPolicy to decide which locales a displayed value may fall back to. chain() returns the requested locale first, then its fallbacks in order.

app/Providers/AppServiceProvider.php
1use Illuminate\Database\Eloquent\Model;
2use Pharaonic\Laravel\Translatable\Contracts\FallbackPolicy;
3 
4public function register()
5{
6 $this->app->singleton(FallbackPolicy::class, function () {
7 return new class implements FallbackPolicy {
8 public function chain(Model $model, string $field, string $locale): array
9 {
10 return $locale === 'ar-EG' ? ['ar-EG', 'ar', 'en'] : [$locale, 'en'];
11 }
12 };
13 });
14}

#Generators

#make:translatable

Create a translatable model, its translation model under the table strategy, and with -m its migrations.

Terminal
php artisan make:translatable Post -m
php artisan make:translatable Blog/Post --json -m
php artisan make:translatable Product --columns --locales=en,ar -m
php artisan make:translatable Page --table
Option Description
--table, --json, --columns Write that strategy's marker on the model. Without one, the model has no marker and follows translatable.strategy. At most one.
-m, --migrations Also create the migrations: the model's table, plus the translations table under the table strategy.
--locales=en,ar The locale columns of the columns strategy. Defaults to app.locale and app.fallback_locale.

The model goes to app/Models when that folder exists, else to app. The command never overwrites a file; it reports the existing file and exits with 1.

The translations-table migration has the locale column, the unique index on the foreign key and locale, and a foreign key that cascades deletes.

#Customizing the Stubs

Terminal
php artisan vendor:publish --tag=translatable-stubs

Edit the copies in stubs/translatable: model.stub, model.translation.stub, migration.create.stub and migration.add.stub. The generators use a published stub instead of the package's.

#translatable:inspect

Show a model's strategy, where it comes from, its fields, and which layouts have a schema and data.

Terminal
php artisan translatable:inspect 'App\Models\Post'
php artisan translatable:inspect 'App\Models\Post' --json

#translatable:make-schema

Write a migration that adds another strategy's storage to an existing model, for you to review and run.

Terminal
php artisan translatable:make-schema 'App\Models\Post' --to=json
php artisan translatable:make-schema 'App\Models\Post' --to=columns --locales=en,ar,fr
php artisan translatable:make-schema 'App\Models\Post' --to=table

--to=table needs the translation model first. Its foreign key column gets the exact type of the model's key (increments, bigIncrements, UUID, ULID or string), read from the database, so MySQL and PostgreSQL accept the foreign key. When the type can't be read, the command warns you to check the column.

#Changing Strategy

Changing a marker or translatable.strategy never moves data. To move a model to another strategy, copy its translations first, then switch.

#1. Inspect

Terminal
php artisan translatable:inspect 'App\Models\Post'

#2. Create the New Storage

Terminal
php artisan translatable:make-schema 'App\Models\Post' --to=json
php artisan migrate

#3. Copy

translatable:migrate is a dry run by default. It reports what it would copy and any conflicts. Add --apply to write.

Terminal
php artisan translatable:migrate 'App\Models\Post' --from=table --to=json
php artisan translatable:migrate 'App\Models\Post' --from=table --to=json --apply
Option Description
--from, --to The source and target layouts: table, json or columns.
--apply Write the target. Without it (or with --dry-run) the command only reports.
--chunk=500 Records per transaction.
--resume / --migration-id= Continue the latest unfinished migration, or a given one.
--fields=title,content Copy only these fields (partial backfill).
--ignore-columns= Extra translation-table columns whose data may stay behind.
--without-scopes Include records hidden by global scopes, such as a tenant scope. Soft-deleted records are always included.
--json Print the report as JSON.

The source is never changed. Each record whose target differs from the source is written with the source's values, and the target's previous values are journaled in storage/translatable/migrations, so an interrupted copy can resume and an applied one can be undone. When the target cannot hold the source (a locale without a column, or translation-table columns that would stay behind), the copy is blocked, nothing is written, and the command exits with 1.

#4. Verify

Terminal
php artisan translatable:verify 'App\Models\Post' --from=table --to=json

It compares every record and exits with 1 when any differs.

#5. Switch

Deploy the marker (implements JsonTranslatable) or the configuration. The old storage stays until you drop it yourself.

#Undo

Terminal
php artisan translatable:rollback 'App\Models\Post' --migration-id=<id> # report
php artisan translatable:rollback 'App\Models\Post' --migration-id=<id> --apply

Rollback writes the journaled previous values back to the target.

#Octane & Queues

The package is safe under Laravel Octane and in queue workers:

  • pending translation changes live on each model instance, never in a shared service;
  • translatable.strategy, app.locale and app.fallback_locale are read on every call, so each request's App::setLocale() applies;
  • request-bound services (your FallbackPolicy, database transactions) are resolved from the current request's container;
  • the shared caches hold only class metadata and table column lists, keyed by connection, database and table, so tenants on other databases never share them.
Reload After Schema Changes

Each worker reads a table's columns once. After a migration that adds a locale column (columns strategy) or a translated column, run php artisan octane:reload or php artisan queue:restart so running workers see it. A normal deploy restarts them anyway.

In a queued job, set the locale you want before reading displayed values, because a worker has no request locale:

app/Jobs/SendDigest.php
1public function handle()
2{
3 App::setLocale($this->user->locale);
4 
5 $title = $this->post->title;
6}

#AI Ready

Laravel Translatable is AI ready. It ships Laravel Boost resources, so the coding agent in your application (Claude Code, Cursor, Codex, Copilot, Gemini CLI, Junie…) knows how to use the package.

#Install

With Laravel Boost in your application, run:

Terminal
php artisan boost:install

Boost finds the package's guideline and skill in vendor/ and adds them for the agents you choose. After updating the package, refresh them with:

Terminal
php artisan boost:update

#What the Agent Learns

Resource Loaded Covers
Guideline (resources/boost/guidelines/core.blade.php) In every session The three strategies, declaring fields, Laravel's locales, and the main reads, writes and scopes
Skill translatable-development When the agent works on translations Every public method and scope, field types, the table schema, events, the Artisan commands, moving between strategies, pitfalls and testing
Keep Them Current

Add @php artisan boost:update --ansi to your Composer post-update-cmd scripts so the agent always matches the installed release.

#Upgrading from 2.x

The table strategy is the default and keeps the 2.x storage, so an existing database needs no migration. Make these changes, then run your tests.

#Configuration

  • The configuration is config/translatable.php with one key, strategy. config/Pharaonic/translatable.php is no longer published or read.
  • 2.x fell back to config('Pharaonic.translatable.default') or en. Set app.fallback_locale to that locale instead.

#Models

  • Rename $translatableAttributes to $translatables. The old name is deprecated but still read when $translatables is missing.
  • $fillable is no longer changed for you. Add locale (or your $translationsKey) or the translated fields yourself.
  • The translations payload only accepts translated fields; any other key throws UnknownTranslatableFieldException.
  • Use the Translatable trait only: Traits\Actions and Traits\Scopes are merged into it.
  • A translated field cannot have a set mutator. Transform the value before setting it.
  • translations and locales cannot be translated field names.

#Behavior

  • $post->title reads the current locale on every access, and setting it now stores the value on save() (2.x dropped it).
  • Translated values are no longer raw attributes: use getDirtyTranslations(), isTranslationDirty() and wasTranslationChanged() instead of getDirty().
  • save() is transactional and never deletes translations. Use forgetTranslation() or forgetTranslations().
  • The protected getTranslation(?string $locale) is gone. getTranslation('title', 'ar') is public and returns a value.
  • translated('ar') needs at least one field with an Arabic value, and translated() without a locale filters by the current locale. 2.x only eager loaded; use withTranslations() for that.
  • whereTranslation() no longer applies its operator to the locale, and only accepts the listed operators and whereHas / orWhereHas.
  • translateOrDefault() falls back to app.fallback_locale.
  • make:translatable renders stubs, takes --table, --json, --columns and -m, and never overwrites files.

The full list is in UPGRADING.md in the repository.

#API Reference

#Reading

Method Description Returns
getTranslation(string $field, ?string $locale = null, bool $fallback = false) The exact value, or the displayed value with $fallback mixed
getTranslations(?string $field = null) locale => value of a field, or field => [locale => value] array
getTranslationsForLocale(string $locale) field => value of a locale array
getTranslatedLocales() Locales with at least one value array
resolveTranslation(string $field, ?string $locale = null) The displayed value and where it came from ResolvedTranslation
getTranslationOrFail(string $field, ?string $locale = null) The exact value, or throws MissingTranslationException mixed
hasTranslation(?string $locale = null, ?string $field = null) Whether a value exists bool
hasCompleteTranslation(string $locale) Whether every required field has a value bool
missingTranslations(string $locale) Required fields without a value array
translationProgress(string $locale) Percentage of required fields with a value int

#Writing

Method Description Returns
setTranslation(string $field, string $locale, mixed $value) Stage one value $this
setTranslations(string $field, array $values) Stage locale => value $this
fillTranslations(array $translations) Stage locale => [field => value] $this
forgetTranslation(string $field, string $locale) Stage the removal of one value $this
forgetTranslations(string $locale) Stage the removal of a locale $this

#Dirty Tracking

Method Description Returns
getDirtyTranslations() Unsaved changes, null for removals array
isTranslationDirty(?string $field = null, ?string $locale = null) Whether there are unsaved changes bool
getTranslationChanges() Changes stored by the last save array
wasTranslationChanged(?string $field = null, ?string $locale = null) Whether the last save changed it bool

#translate() and the Table Strategy

Method Description Returns
translate(?string $locale = null) The locale's translation, or null Model|LocaleTranslation|null
translateOrNew(string $locale) The locale's translation, created when missing Model|LocaleTranslation
translateOrDefault(?string $locale = null) The locale's, else the fallback locale's Model|LocaleTranslation|null
translateOrFail(string $locale) The locale's, or throws NotFoundHttpException Model|LocaleTranslation
translations() The HasMany relation (table strategy only) HasMany
$model->translations Table: translation models keyed by locale. Others: getTranslations() Collection|array
$model->locales getTranslatedLocales() array

#Scopes

Scope Description
translated(?string $locale = null) At least one field has a value in the locale
notTranslated(?string $locale = null) No field has a value in the locale
whereHasTranslation(string $locale, ?string $field = null) The field (or any field) has a value
whereMissingTranslation(string $locale, ?string $field = null) The field (or every field) has no value
whereTranslation(string $field, mixed $value, ?string $locale = null, string $action = 'whereHas', string $op = '=') Compare a value
orWhereTranslation(string $field, mixed $value, ?string $locale = null) or equality
whereTranslationLike(string $field, string $pattern, ?string $locale = null) like
orWhereTranslationLike(string $field, string $pattern, ?string $locale = null) or like
whereTranslationIn(string $field, iterable $values, ?string $locale = null) in
whereTranslationNotIn(string $field, iterable $values, ?string $locale = null) not in
whereTranslationProgress(string $locale, string $operator, int|float $percentage) Compare the completeness percentage
orderByTranslation(string $field, string $direction = 'asc', ?string $locale = null, bool $fallback = false) Sort, missing values last
translatedSorting(string $locale, string $field, string $method = 'asc') 2.x: translated in the locale, sorted, then by key
withTranslations(string|array|null $locales = null) Eager load (table strategy)

#Classes

Class Description
Translatable The model trait
Contracts\TableTranslatable, JsonTranslatable, ColumnsTranslatable Strategy markers
Contracts\FallbackPolicy chain(Model $model, string $field, string $locale): array
Data\ResolvedTranslation field, value, requestedLocale, resolvedLocale, isFallback, isMissing
Data\LocaleTranslation One locale of a json or columns model: getLocale(), getModel(), property and array access, toArray()

#Exceptions

Every exception implements Exceptions\TranslatableException.

Exception Thrown when
InvalidTranslationStrategyException The configured strategy is not table, json or columns
ConflictingTranslationStrategiesException A model implements more than one marker
InvalidTranslatableDefinitionException A field definition breaks a rule
InvalidLocaleException A locale is malformed
UnknownTranslatableFieldException A field is not translated
InvalidTranslationValueException A value doesn't match the field's type
MissingTranslationException getTranslationOrFail() finds no value
TranslationConflictException A save keeps conflicting after its retries
TranslationSchemaException The storage a strategy needs is missing
UnsupportedTranslationQueryException A query or method doesn't fit the strategy

#Examples

#1. A Multilingual Blog

A table-strategy post with typed, required fields and a locale from the URL.

app/Models/Post.php
1namespace App\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4use Pharaonic\Laravel\Translatable\Translatable;
5 
6class Post extends Model
7{
8 use Translatable;
9 
10 protected $fillable = ['published', 'locale'];
11 
12 public function translatable(): array
13 {
14 return [
15 'title' => ['type' => 'string', 'required' => true],
16 'content' => ['required' => true],
17 ];
18 }
19}
app/Http/Middleware/SetLocale.php
1namespace App\Http\Middleware;
2 
3use Closure;
4use Illuminate\Support\Facades\App;
5 
6class SetLocale
7{
8 public function handle($request, Closure $next)
9 {
10 App::setLocale($request->route('locale'));
11 
12 return $next($request);
13 }
14}
app/Http/Controllers/PostController.php
1namespace App\Http\Controllers;
2 
3use App\Models\Post;
4 
5class PostController extends Controller
6{
7 public function index(string $locale)
8 {
9 $posts = Post::whereTranslationProgress($locale, '>=', 100)
10 ->orderByTranslation('title', 'asc', $locale)
11 ->paginate();
12 
13 return view('posts.index', compact('posts'));
14 }
15 
16 public function show(string $locale, Post $post)
17 {
18 abort_unless($post->hasCompleteTranslation($locale), 404);
19 
20 return view('posts.show', compact('post'));
21 }
22}
routes/web.php
1use App\Http\Controllers\PostController;
2 
3Route::middleware('locale')->prefix('{locale}')->group(function () {
4 Route::get('posts', [PostController::class, 'index']);
5 Route::get('posts/{post}', [PostController::class, 'show']);
6});

#2. Saving a Form with Every Locale

The locale payload key fills several locales at once when it is fillable.

app/Http/Controllers/Admin/PostController.php
1public function store(Request $request)
2{
3 $data = $request->validate([
4 'published' => 'boolean',
5 'locale' => 'required|array',
6 'locale.en.title' => 'required|string',
7 'locale.ar.title' => 'nullable|string',
8 'locale.*.content' => 'nullable|string',
9 ]);
10 
11 $post = Post::create($data); // one transaction for the post and its translations
12 
13 return redirect()->route('admin.posts.edit', $post);
14}

#3. A Translation Dashboard

List what still needs translating, per locale.

1$locale = 'ar';
2 
3$pending = Post::whereTranslationProgress($locale, '<', 100)->get()
4 ->map(function (Post $post) use ($locale) {
5 return [
6 'id' => $post->id,
7 'title' => $post->getTranslation('title', 'en'),
8 'missing' => $post->missingTranslations($locale),
9 'progress' => $post->translationProgress($locale),
10 ];
11 });

#4. A JSON Catalog

Products with typed translated fields in JSON columns.

app/Models/Product.php
1class Product extends Model implements JsonTranslatable
2{
3 use Translatable;
4 
5 public function translatable(): array
6 {
7 return [
8 'name' => ['type' => 'string', 'required' => true],
9 'features' => ['type' => 'array'],
10 ];
11 }
12}
1$product = new Product;
2$product->setTranslation('features', 'en', ['Waterproof', 'Bluetooth'])->save();
3 
4$product->getTranslation('features', 'en'); // ['Waterproof', 'Bluetooth']
5Product::whereTranslationLike('name', 'Phone%', 'en')->get();

#5. Moving a Model from Table to Columns

Terminal
php artisan translatable:make-schema 'App\Models\Post' --to=columns --locales=en,ar
php artisan migrate
php artisan translatable:migrate 'App\Models\Post' --from=table --to=columns --apply
php artisan translatable:verify 'App\Models\Post' --from=table --to=columns

Then add implements ColumnsTranslatable to the model and deploy.

#Troubleshooting

#My translations disappeared after changing the strategy

Changing a marker or translatable.strategy doesn't move data, so the model now reads the new, empty storage. Switch back, then copy the data with translatable:migrate before switching again (see Changing Strategy).

#Setting a locale throws TranslationSchemaException

The model uses the columns strategy and the table has no {field}_{locale} column for that locale. Add the column with translatable:make-schema --to=columns --locales=… and migrate. Under Octane or queue workers, reload them afterwards.

#$post->title shows another language

The current locale has no value, so the displayed value comes from app.fallback_locale. Use getTranslation('title') for the exact value, resolveTranslation('title')->isFallback to detect it, or 'fallback' => false on the field to turn it off.

#isDirty() is false after setting a translation

Translated values are not model attributes. Use isTranslationDirty() and getDirtyTranslations().

#Mass assignment ignores the translations

$fillable is not changed for you. Add the translated fields, or the locale payload key, to $fillable.

#InvalidTranslatableDefinitionException on a field

The field has a set mutator, uses a reserved name (translations, locales or the key), has an unknown option, or translatable() and $translatables list different fields. The message names the cause.

#The foreign key of a generated translations table fails on MySQL

The foreign key column must have the exact type of the model's key. translatable:make-schema --to=table reads it from the database; if it warned that it couldn't, change the column by hand (unsignedInteger for increments, uuid or char for UUID keys).

#A column on a columns-strategy table is treated as a locale

Any column named like a translated field followed by two or three letters (title_xx) is read as a locale of that field. Rename the column.

Contributors

Amazing people who made this package possible

This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel Translatable!

Moamen Eltouny

@MoamenEltouny

89 contributions

Chun-Sheng, Li

@peter279k

1 contribution

Want to Contribute?

We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.