[Deprecated] A Laravel package for multilingual models
[Deprecated] A Laravel package for multilingual models
This package has been deprecated. But worry not. You can use Astrotomic/laravel-translatable.
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.
Getting translated attributes
$greece = Country::where('code', 'gr')->first();
echo $greece->translate('en')->name; // Greece
App::setLocale('en');
echo $greece->name; // Greece
App::setLocale('de');
echo $greece->name; // GriechenlandSaving translated attributes
$greece = Country::where('code', 'gr')->first();
echo $greece->translate('en')->name; // Greece
$greece->translate('en')->name = 'abc';
$greece->save();
$greece = Country::where('code', 'gr')->first();
echo $greece->translate('en')->name; // abcFilling multiple translations
$data = [
'code' => 'gr',
'en' => ['name' => 'Greece'],
'fr' => ['name' => 'Grèce'],
];
$greece = Country::create($data);
echo $greece->translate('fr')->name; // Grèce| Laravel | Translatable |
|---|---|
| 5.8 | 9.* |
| 5.7 | 9.* |
| 5.6 | 9.* |
| 5.5 | 8.* |
| 5.4 | 7.* |
| 5.3 | 6.* |
| 5.2 | 5.5 - 6.* |
| 5.1 | 5.0 - 6.* |
| 5.0 | 5.0 - 5.4 |
| 4.2.x | 4.4.x |
| 4.1.x | 4.4.x |
| 4.0.x | 4.3.x |
Add the package in your composer.json by executing the command.
composer require dimsav/laravel-translatableNext, add the service provider to app/config/app.php
Dimsav\Translatable\TranslatableServiceProvider::class,In this example, we want to translate the model Country. We will need an extra table country_translations:
Schema::create('countries', function(Blueprint $table)
{
$table->increments('id');
$table->string('code');
$table->timestamps();
});
Schema::create('country_translations', function(Blueprint $table)
{
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->string('name');
$table->string('locale')->index();
$table->unique(['country_id','locale']);
$table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
});Country should use the trait Dimsav\Translatable\Translatable. CountryTranslation.// models/Country.php
class Country extends Eloquent {
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['name'];
protected $fillable = ['code'];
/**
* The relations to eager load on every query.
*
* @var array
*/
// (optionaly)
// protected $with = ['translations'];
}
// models/CountryTranslation.php
class CountryTranslation extends Eloquent {
public $timestamps = false;
protected $fillable = ['name'];
}The array $translatedAttributes contains the names of the fields being translated in the "Translation" model.
We copy the configuration file to our project.
Laravel 5.*
php artisan vendor:publish --tag=translatable Laravel 4.*
php artisan config:publish dimsav/laravel-translatableNote: There isn't any restriction for the format of the locales. Feel free to use whatever suits you better, like "eng" instead of "en", or "el" instead of "gr". The important is to define your locales and stick to them.
You can see the options for further customization in the config file.
The convention used to define the class of the translation model is to append the keyword Translation.
So if your model is \MyApp\Models\Country, the default translation would be \MyApp\Models\CountryTranslation.
To use a custom class as translation model, define the translation class (including the namespace) as parameter. For example:
<?php
namespace MyApp\Models;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Country extends Eloquent
{
use Translatable;
public $translationModel = 'MyApp\Models\CountryAwesomeTranslation';
}
Please read the installation steps first, to understand what classes need to be created.
……To use the magic properties, you have to define the property $translatedAttributes in your
main model:
class Country extends Eloquent {
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['name'];
}// Again we start by having a country instance
$germany = Country::where('code', 'de')->first();
// We can reference properties of the translation object directly from our main model.
// This uses the default locale and is the equivalent of $germany->translate()->name
$germany->name; // 'Germany'
// We can also quick access a translation with a custom locale
$germany->{'name:de'} // 'Deutschland'If you want to fallback to a default translation when a translation has not been found, enable this in the configuration
using the use_fallback key. And to select the default locale, use the fallback_locale key.
Configuration example:
return [
'use_fallback' => true,
'fallback_locale' => 'en',
];You can also define per-model the default for "if fallback should be used", by setting the $useTranslationFallback property:
class Country {
public $useTranslationFallback = true;
}Even though we try having all models nicely translated, some fields might left empty. What's the result? You end up with missing translations for those fields!
The property fallback feature is here to help. When enabled, translatable will return the value of the fallback language for those empty properties.
The feature is enabled by default on new installations. If your config file was setup before v7.1, make sure to add the following line to enable the feature:
'use_property_fallback' => true,Of course the fallback locales must be enabled to use this feature.
If the property fallback is enabled in the configuration, then translatable will return the translation of the fallback locale for the fields where the translation is empty.
This package is made to translate strings, but in general it's also able to translate numbers, bools or whatever you want to. By default a simple empty() call is used to detect if the translation value is empty or not. If you want to customize this or use different logic per property you can override isEmptyTranslatableAttribute() in your main model.
protected function isEmptyTranslatableAttribute(string $key, $value): bool
{
switch($key) {
case 'name':
return empty($value);
case 'price':
return !is_number($value);
default:
return is_null($value);
}
}Since version v5.3 it is possible to use country based locales. For example, you can have the following locales:
eneses-MXes-COTo configuration for these locales looks like this:
'locales' => [
'en',
'es' => [
'MX',
'CO',
],
];We can also configure the "glue" between the language and country. If for instance we prefer the format es_MX instead of es-MX,
the configuration should look like this:
'locale_separator' => '_',What applies for the fallback of the locales using the en-MX format?
Let's say our fallback locale is en. Now, when we try to fetch from the database the translation for the
locale es-MX but it doesn't exist, we won't get as fallback the translation for en. Translatable will use as a
fallback es (the first part of es-MX) and only if nothing is found, the translation for en is returned.
If the toArray() method is called it's possible to autoload all translations. To control this feature the package comes with a config value to_array_always_loads_translations and three static methods in the trait:
enableAutoloadTranslations() - forces to load all translationsdisableAutoloadTranslations() - disables autoload and returns parent attributesdefaultAutoloadTranslations() - does not change the default behavior logic (default)Thanks to the community a few packages have been written to make usage of Translatable easier when working with forms:
Examples for all the package features can be found in the code used for the tests.
Got any question or suggestion? Feel free to open an Issue.
You are awesome! Watch the repo and reply to the issues. You will help offering a great experience to the users of the package. #communityWorks
Also buy me a beer by making a donation. ❤️
Translatable is fully compatible with all kinds of Eloquent extensions, including Ardent. If you need help to implement Translatable with these extensions, see this example.
Please see the installation steps to understand how your database should be structured.
If your properties are written in english, we recommend using these commands in your migrations:
// We insert the translation attributes into the fresh translated table:
\DB::statement("insert into country_translations (country_id, name, locale) select id, name, 'en' from countries");
// We drop the translation attributes in our main table:
Schema::table('countries', function ($table) {
$table->dropColumn('name');
}); A tip here is to make the MySQL query first and then do the Eloquent one.
To fetch a list of records ordered by a translated field, you can do this:
SELECT * from counNo open issues yet, or sync has not completed.