Database Localisation
2 minute read
Why
Database localisation is important for strings that do not belong in front end code. Things like permission names, genders, titles, and so on. The following steps walk you through adding database localisation to your feature.
1. Add a migration to your table
The standard column name to use is i18n_key
(type TEXT
). The key can be nullable
as some tables make use of custom fields, which we cannot translate. If the feature does not make use of custom fields, omit ->nullable()
.
Create a migration to add this column to your table:
class AddI18nKeyToCatsTable extends AbstractTenantMigration
{
public function runUpMigration(): void
{
Schema::table('cats', function (Blueprint $table) {
$table->text('i18n_key')->nullable();
});
}
}
2. Populate the i18n_key
column in your table
Either in the same migration or a new one, you should populate the keys to your table:
$migrationArray = [
['id' => '1', 'i18n_key' => 'animals:cats.scottishFold'],
['id' => '2', 'i18n_key' => 'animals:cats.russianBlue'],
];
foreach ($migrationArray as $cat) {
DB::table('cats')
->where('id', '=', $cat['id'])
->update(['i18n_key' => $cat['i18n_key']])
}
3. Use the HasTranslatedNameColumnTrait
trait in your model
This trait overrides the normal name
attribute to make use of your translations.
In the use
statements in EloquentCat.php
:
use Lapis\Domain\Core\Database\HasTranslatedNameColumnTrait;
And in the EloquentCat
class:
class EloquentCat extends Model
{
use HasTranslatedNameColumnTrait;
...
}
Every time we do $cat->name
from now on, it will try to access the localised name of the cat. It will fall back to the original name if no localisation exists.
4. Add your translations to the relevant .yml
file
Once you have your database migration done and the code side done, you need to add the values to the relevant localisation.
As in our example, let’s add the names to animals.yml
:
cats:
scottishFold: Scottish Fold
russianBlue: Russian Blue
5. Verifying your localisations
To verify your localisations you can the text in the .yml
file and refresh the page that uses the translations.