Skip to main content
Back to packages
1,412 GitHub stars

Astrotomic/laravel-translatable

View on GitHub

Description

If you want to store translations of your models into the database, this package is for you.

This is a Laravel package for translatable models. Its goal is to remove the complexity in retrieving and storing multilingual model instances. With this package you write less code, as the translations are being fetched/saved when you fetch/save your instance.

Quick Example

Getting translated attributes

$post = Post::first();
echo $post->translate('en')->title; // My first post
 
App::setLocale('en');
echo $post->title; // My first post
 
App::setLocale('de');
echo $post->title; // Mein erster Post

Saving translated attributes

$post = Post::first();
echo $post->translate('en')->title; // My first post
 
$post->translate('en')->title = 'My cool post';
$post->save();
 
$post = Post::first();
echo $post->translate('en')->title; // My cool post

Filling multiple translations

$data = [
'author' => 'Gummibeer',
'en' => ['title' => 'My first post'],
'fr' => ['title' => 'Mon premier post'],
];
$post = Post::create($data);
 
echo $post->translate('fr')->title; // Mon premier post

Filling multiple translations wrapped

You may define a wrapper property when creating new translations. Set the translations_wrapper property in translatable config file:

'translations_wrapper' => 'translations',

Then just wrap multiple locales using that property:

$data = [
'author' => 'Gummibeer',
'translations' => [
'en' => ['title' => 'My first post'],
'fr' => ['title' => 'Mon premier post'],
],
];
$post = Post::create($data);
 
echo $post->translate('fr')->title; // Mon premier post

Related Content on Laravel Daily

Video

Recent Courses on Laravel Daily