Making Eloquent models translatable
Spatie, the company where I work, is located in Belgium. Although our country is quite small, there are three official languages: Dutch, French and German. That's why nearly all of our projects are multilingual. In most projects we used to rely on Dimitris Savvopoulos popular translatable package to make Eloquent models translatable. Installing and using it is fairly easy. A downside is that all translations are stored in a separate tables. This means that you need to migrate two tables and manage two models.
Today we released our newest package laravel-translatable. This big difference with Dimitris' package is that translations are stored as json. There is no need for a second table or model. The idea to store translations as json is not ours, we got it from active community member Mohamed Said (be sure to check out his blog).
To make a model translatable you just have to use the HasTranslations
-trait and specify in a property called $translatable
which attributes should be translatable. All translatable attributes should be mapped as a text
-column in the database.
Here's an example of a model which uses HasTranslations
-trait.
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
class NewsItem extends Model
{
use HasTranslations;
public $translatable = ['name'];
}
Once that's done you can do this to work with translations:
$newsItem = new NewsItem; // This is an Eloquent model
$newsItem
->setTranslation('name', 'en', 'Name in English');
->setTranslation('name', 'nl', 'Naam in het Nederlands');
->save();
$newsItem->name; // Returns 'Name in English' given that the current app locale is 'en'
$newsItem->getTranslation('name', 'nl'); // returns 'Naam in het Nederlands'
app()->setLocale('nl');
$newsItem->name; // Returns 'Naam in het Nederlands'
As announced in Mohamed's post Laravel 5.2.23 gained fluent syntax to query json columns. If you use MySQL >= 5.7 and Laravel 5.2.23 you can do this:
NewsItem::where('name->en', 'Name in English')->get();
Awesome right?
Take a look at the package on GitHub to learn all available methods. If you like the package, take a look at the other ones we've previously made.
What are your thoughts on "Making Eloquent models translatable"?