How To Add Multilingual Support to Eloquent

Published on by

How To Add Multilingual Support to Eloquent image

Did you know that several countries throughout the world have more than one official language? For example, my home country Belgium has three; French, Dutch, and German. Most Belgians also speak English.

Laravel’s Eloquent ORM is a very powerful part of Laravel. Unfortunately, it doesn’t provide support for multilingual models out of the box. Adding that functionality yourself isn’t that difficult.

First let’s take a look at a migration with no multilingual support whatsoever:

Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('text');
$table->timestamps();
});

We could easily make the table hold multiple languages by adding columns for the specific languages:

Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('name_en');
$table->text('text_en');
$table->string('name_fr');
$table->text('text_fr');
$table->boolean('online');
$table->timestamps();
});

Now, this table has support for storing text in English and French. However, this approach has a significant drawback: every time you want to add support for a new language you’ll need to add fields to every table with multilingual support. That’s very cumbersome when the amout of languages starts to grow or if you have many multilingual tables.

A better way to go about this is to separate the fields that must be translated to another table.

Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->boolean('online');
$table->timestamps();
});
 
Schema::create('article_translations', function (Blueprint $table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->string('locale')->index();
 
$table->string('name');
$table->text('text');
 
$table->unique(['article_id','locale']);
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
});

Using this migration you don’t need to create extra fields when your application needs to support an extra language.

The locale-field is used to determine the language of the stored record. In the next examples of this article, we are going to store an iso-code in this field.

Adding a foreign key with cascading deletes will make sure that when a record in the articles-table gets removed, it’s corresponding translations will be removed as well.

Ok, now that the database is ready for storing translatable content, let’s think about how we’d like to work with it.

$frenchText = $article->getTranslation('fr')->text;

That’s nice and readable. Be we can do ever better. It would be very useful if the article model would return the French translation of the text when the app’s locale is French:

app()->setLocale('fr');
$frenchText = $article->text;

This will make working with translatable data significantly easier. Consider this small view:

The article with title {{ $article->title }} is {{ $this->online ? 'online' : 'offline' }}.

Notice that there isn’t any difference in using a translated field and a non-translated field. Nice!

You could create the functions to allow for this behaviour yourself, but Dimitris Savvopoulos created a package called laravel-translatable that does all of this and more. I use it on every project.

After installing the service provider you must update your models to use the Translatable-trait. The model should also have a $translatableAttributes-property containing an array with the names of the fields than can be translated:

// app/Article.php
class Article extends Model
{
use \Dimsav\Translatable\Translatable;
 
public $translatedAttributes = ['name', 'text'];
 
...
}
 
// app/ArticleTranslation.php
class ArticleTranslation extends Model
{
public $timestamps = false;
 
...
}

Now that all the setup is completed we can store some new translatable articles. If you’re following along just add this route to your Laravel app.

Route::get('create', function($locale) {
$article = new Article();
$article->online = true;
$article->save();
 
foreach (['en', 'nl', 'fr', 'de'] as $locale) {
$article->translateOrNew($locale)->name = "Title {$locale}";
$article->translateOrNew($locale)->text = "Text {$locale}";
}
 
$article->save();
 
echo 'Created an article with some translations!';
});

When you look in the database after you’ve browsed to ‘/create’ you’ll see that the articles-table holds one record. The article_translations-table contains three records: one for every locale in the example above.

Now let’s retrieve the translations. Add this route to your Laravel app:

Route::get('{locale}', function($locale) {
app()->setLocale($locale);
 
$article = Article::first();
 
return view('article')->with(compact('article'));
});

Add a article.blade.php-view with this content:

<h1>{{ $article->name }}</h1>
{{ $article->text }}

When you browse to ‘/en’ you’ll see the English translations of the article. Browse to ‘/nl’, ‘/fr’ or ‘/de’ to see the localized article for those locales.

Congratulations! You’ve now learned how to add multilingual support to an Eloquent model. I’ve created a repository containing all examples of this post on GitHub. If you want to know more, I recommend reading the examples in the readme of Dimitris’ package. Still hungry for more knowledge? Dive into his package code on GitHub. It’s not that hard to follow, and you’ll learn a lot from it.

Freek Van der Herten photo

PHP developer, Laravel enthousiast at Spatie.be, blogger, and package creator.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article