How To Make Dynamic Translation in Database | Laravel 8

Hi everyone. In this blog, I will show you how to make localization in databas for different tables and contents.
For that have many different ways. But in Laravel have a package laravel-translatable for that. I will show you how to use this package in your project in a good way. The main idea of this package you can use a trait in your model to translate your model. How? I will show now))
This package contains a trait to make Eloquent models translatable. Translations are stored as JSON. There is no extra table needed to hold them.
First of all, we must be install this package with the composer. Execute this command for installation
composer require spatie/laravel-translatable
If you want to have another fallback_locale then the app fallback locale (see config/app.php
), you could publish the config file:
php artisan vendor:publish --provider="Spatie\Translatable\TranslatableServiceProvider"
This is the contents of the published file:
return [
'fallback_locale' => 'en',
];
After installation and configuration is completed now we must translate our models.
The required steps to make a model translatable are:
- First, you need to add the
Spatie\Translatable\HasTranslations
-trait. - Next, you should create a public property
$translatable
which holds an array with all the names of attributes you wish to make translatable. - Finally, you should make sure that all translatable attributes are set to the
text
-datatype in your database. If your database supportsjson
-columns, use that.
Here’s an example of a prepared model:

Available methods
Getting a translation
The easiest way to get a translation for the current locale is to just get the property for the translated attribute. For example (given that name
is a translatable attribute):
$newsItem->name;
You can also use this method:
public function getTranslation(string $attributeName, string $locale, bool $useFallbackLocale = true) : string
This function has an alias named translate
.
Getting all translations
You can get all translations by calling getTranslations()
without an argument:
$newsItem->getTranslations();
Or you can use the accessor
$yourModel->translations
Setting a translation
The easiest way to set a translation for the current locale is to just set the property for a translatable attribute. For example (given that name
is a translatable attribute):
$newsItem->name = 'New translation';
Also you can set translations with
$newItem->name = ['en' => 'myName', 'nl' => 'Naam in het Nederlands'];
To set a translation for a specific locale you can use this method:
public function setTranslation(string $attributeName, string $locale, string $value)
To actually save the translation, don't forget to save your model.
$newsItem->setTranslation('name', 'en', 'Updated name in English');
$newsItem->save();
Validation
- if you want to validate an attribute for uniqueness before saving/updating the db, you might want to have a look at laravel-unique-translation which is made specifically for laravel-translatable.
Forgetting a translation
You can forget a translation for a specific field:
public function forgetTranslation(string $attributeName, string $locale)
You can forget all translations for a specific locale:
public function forgetAllTranslations(string $locale)
Getting all translations in one go
public function getTranslations(string $attributeName): array
Setting translations in one go
public function setTranslations(string $attributeName, array $translations)
Here’s an example:

Replace translations in one go
You can replace all the translations for a single key using this method:

Here’s an example:

Setting the model locale
The default locale used to translate models is the application locale, however it can sometimes be handy to use a custom locale.
To do so, you can use setLocale
on a model instance.

Alternatively, you can use usingLocale
static method:

Events
TranslationHasBeenSet
Right after calling setTranslation
the Spatie\Translatable\Events\TranslationHasBeenSet
-event will be fired.
It has these properties:

Creating models
You can immediately set translations when creating a model. Here’s an example:

Querying translatable attributes
If you’re using MySQL 5.7 or above, it’s recommended that you use the json data type for housing translations in the db. This will allow you to query these columns like this:

Or if you’re using MariaDB 10.2.3 or above :

Automatically display the right translation when displaying model
Many times models using HasTranslation
trait may be directly returned as response content. In this scenario, and similar ones, the toArray()
method on Model
class is called under the hood to serialize your model; it accesses directly the $attributes field to perform the serialization, bypassing the translatable feature (which is based on accessors and mutators) and returning the text representation of the stored JSON instead of the translated value.
The best way to make your model automatically return translated fields is to wrap Spatie\Translatable\HasTranslations
trait into a custom trait which overrides the toArray()
method to automatically replace all translatable fields content with their translated value, like in the following example, and use it instead of the default one.

Thank you for reading this blog. If you like my content please clap for responding to me and follow for new content.