Writing Translations - nevadskiy/laravel-translatable Wiki

You can set attribute translations as you would with regular model attributes.

app()->setLocale('uk');

$book->title = "П'ятдесят верстов";

This method simply sets the translation of the attribute in the current application locale, but does not save it to the database yet.

To save the values of translatable attributes in the database, you need to call the save method as you would with a normal model.

app()->setLocale('uk');

$book = new Book();
$book->title = "П'ятдесят верстов";
$book->save();

Also, other Eloquent methods like create or update work with translatable attributes as usual.

All casts, mutators, and accessors will be applied automatically, so no additional action is required.

Translator instance

When interacting with translatable model attributes, the model internally delegates all operations to the Translator instance.

But you can interact with the Translator directly to gain more control over the translatable attributes.

To set the translation of the attribute using Translation instance:

$book = new Book();
$book->translator()->set('title', "Fifty miles", 'en');
$book->translator()->set('title', "П'ятдесят верстов", 'uk');
$book->save();

If the last argument $locale is not passed, then the current application locale will be used.

TranslationSet

To add translations to an attribute for multiple locales at once, you can use the TranslationSet class:

use Nevadskiy\Translatable\TranslationSet;

$book->title = new TranslationSet([
    'en' => "Fifty miles",
    'uk' => "П'ятдесят верстов",
    'pl' => "Pięćdziesiąt mil",
])

This can be useful in many cases, such as database seeders:

<?php

namespace Database\Seeders;

use App\Models\Book;
use Illuminate\Database\Seeder;
use Nevadskiy\Translatable\TranslationSet;

class BookSeeder extends Seeder
{
    public function run(): void
    {
        foreach ($this->books() as $attributes) {
            Book::create($attributes);
        }
    }

    private function books(): array
    {
        return [
            [
                'title' => new TranslationSet([
                    'en' => "Fifty miles",
                    'uk' => "П'ятдесят верстов",
                    'pl' => "Pięćdziesiąt mil",
                ]),
                'pages' => 15,
            ],
            [
                'title' => new TranslationSet([
                    'en' => "People's Malachi",
                    'uk' => "Народний Малахій",
                    'pl' => "Malachiasz Ludowy",
                ]),
                'pages' => 20,
            ],
        ];
    }
}