2017 © Pedro Peláez
 

library laravel-translatable

A Laravel package for multilingual models

image

dimsav/laravel-translatable

A Laravel package for multilingual models

  • Wednesday, July 25, 2018
  • by dimsav
  • Repository
  • 76 Watchers
  • 1605 Stars
  • 603,279 Installations
  • PHP
  • 73 Dependents
  • 0 Suggesters
  • 281 Forks
  • 27 Open issues
  • 49 Versions
  • 9 % Grown

The README.md

This package has been deprecated. But worry not. You can use Astrotomic/laravel-translatable., (*1)


Laravel-Translatable

Total Downloads Build Status Code Coverage Latest Stable Version License SensioLabsInsight StyleCI, (*2)

Laravel Translatable, (*3)

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

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., (*5)

Docs

Demo

Getting translated attributes, (*6)

  $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;     // Griechenland

Saving translated attributes, (*7)

  $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; // abc

Filling multiple translations, (*8)

  $data = [
    'code' => 'gr',
    'en'  => ['name' => 'Greece'],
    'fr'  => ['name' => 'Grèce'],
  ];

  $greece = Country::create($data);

  echo $greece->translate('fr')->name; // Grèce

Laravel compatibility

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

Tutorials

Installation in 4 steps

Step 1: Install package

Add the package in your composer.json by executing the command., (*9)

composer require dimsav/laravel-translatable

Next, add the service provider to app/config/app.php, (*10)

Dimsav\Translatable\TranslatableServiceProvider::class,

Step 2: Migrations

In this example, we want to translate the model Country. We will need an extra table country_translations:, (*11)

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');
});

Step 3: Models

  1. The translatable model Country should use the trait Dimsav\Translatable\Translatable.
  2. The convention for the translation model is 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., (*12)

Step 4: Configuration

We copy the configuration file to our project., (*13)

Laravel 5.*, (*14)

php artisan vendor:publish --tag=translatable 

Laravel 4.*, (*15)

php artisan config:publish dimsav/laravel-translatable

Note: 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., (*16)

Configuration

The config file

You can see the options for further customization in the config file., (*17)

The translation model

The convention used to define the class of the translation model is to append the keyword Translation., (*18)

So if your model is \MyApp\Models\Country, the default translation would be \MyApp\Models\CountryTranslation., (*19)

To use a custom class as translation model, define the translation class (including the namespace) as parameter. For example:, (*20)

<?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';
}

Features list

Please read the installation steps first, to understand what classes need to be created., (*21)

Available methods

// Before we get started, this is how we determine the default locale.
// It is set by laravel or other packages.
App::getLocale(); // 'fr' 

// To use this package, first we need an instance of our model
$germany = Country::where('code', 'de')->first();

// This returns an instance of CountryTranslation of using the default locale.
// So in this case, french. If no french translation is found, it returns null.
$translation = $germany->translate();

// It is possible to define a default locale per model by overriding the model constructor.
public function __construct(array $attributes = [])
{
    parent::__construct($attributes);

    $this->defaultLocale = 'de';
}

// It is also possible to define a default locale for our model on the fly:
$germany->setDefaultLocale('de');

// If an german translation exists, it returns an instance of 
// CountryTranslation. Otherwise it returns null.
$translation = $germany->translate('de');

// If a german translation doesn't exist, it attempts to get a translation  
// of the fallback language (see fallback locale section below).
$translation = $germany->translate('de', true);

// Alias of the above.
$translation = $germany->translateOrDefault('de');

// Returns instance of CountryTranslation of using the default locale.
// If no translation is found, it returns a fallback translation
// if enabled in the configuration.
$translation = $germany->getTranslation();

// If an german translation exists, it returns an instance of 
// CountryTranslation. Otherwise it returns null.
// Same as $germany->translate('de');
$translation = $germany->getTranslation('de', true);

// To set the translation for a field you can either update the translation model.
// Saving the model will also save all the related translations.
$germany->translate('en')->name = 'Germany';
$germany->save();

// Alternatively we can use the shortcut
$germany->{'name:en'} = 'Germany';
$germany->save();

// There are two ways of inserting mutliple translations into the database
// First, using the locale as array key.
$greece = $country->fill([
    'en'  => ['name' => 'Greece'],
    'fr'  => ['name' => 'Grèce'],
]);

// The second way is to use the following syntax.  
$greece = $country->fill([
    'name:en' => 'Greece',
    'name:fr' => 'Grèce',
]);

// Returns true/false if the model has translation about the current locale. 
$germany->hasTranslation();

// Returns true/false if the model has translation in french. 
$germany->hasTranslation('fr');

// If a german translation doesn't exist, it returns
// a new instance of CountryTranslation.
$translation = $germany->translateOrNew('de');

// Returns a new CountryTranslation instance for the selected
// language, and binds it to $germany
$translation = $germany->getNewTranslation('it');

// The eloquent model relationship. Do what you want with it ;) 
$germany->translations();

// Remove all translations linked to an object
$germany->deleteTranslations();

// Delete one or multiple translations
$germany->deleteTranslations('de');
$germany->deleteTranslations(['de', 'en']);

// Gel all the translations as array
$germany->getTranslationsArray();
// Returns
[
 'en' => ['name' => 'Germany'],
 'de' => ['name' => 'Deutschland'],
 'fr' => ['name' => 'Allemagne'],
];

// Creates a clone and clones the translations
$replicate = $germany->replicateWithTranslations(); 

Available scopes

// Returns all countries having translations in english
Country::translatedIn('en')->get();

// Returns all countries not being translated in english
Country::notTranslatedIn('en')->get();

// Returns all countries having translations
Country::translated()->get();

// Eager loads translation relationship only for the default
// and fallback (if enabled) locale
Country::withTranslation()->get();

// Returns an array containing pairs of country ids and the translated
// name attribute. For example: 
// [
//     ['id' => 1, 'name' => 'Greece'], 
//     ['id' => 2, 'name' => 'Belgium']
// ]
Country::listsTranslations('name')->get()->toArray();

// Filters countries by checking the translation against the given value 
Country::whereTranslation('name', 'Greece')->first();

// Filters countries by checking the translation against the given value, only in the specified locale
Country::whereTranslation('name', 'Greece', 'en')->first();

// Or where translation
Country::whereTranslation('name', 'Greece')->orWhereTranslation('name', 'France')->get();

// Filters countries by checking the translation against the given string with wildcards
Country::whereTranslationLike('name', '%Gree%')->first();

// Or where translation like
Country::whereTranslationLike('name', '%eece%')->orWhereTranslationLike('name', '%ance%')->get();

Magic properties

To use the magic properties, you have to define the property $translatedAttributes in your main model:, (*22)

```php class Country extends Eloquent {, (*23)

 use \Dimsav\Translatable\Translatable;

 public $translatedAttributes = ['name'];

} ```, (*24)

// 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'

Fallback

Fallback locales

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., (*25)

Configuration example:, (*26)

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:, (*27)

class Country {

    public $useTranslationFallback = true;

}

Fallback per property

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!, (*28)

The property fallback feature is here to help. When enabled, translatable will return the value of the fallback language for those empty properties., (*29)

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:, (*30)

'use_property_fallback' => true,

Of course the fallback locales must be enabled to use this feature., (*31)

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., (*32)

customize empty translation property detection

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., (*33)

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);
    }
}

Country based fallback

Since version v5.3 it is possible to use country based locales. For example, you can have the following locales:, (*34)

  • English: en
  • Spanish: es
  • Mexican Spanish: es-MX
  • Colombian Spanish: es-CO

To configuration for these locales looks like this:, (*35)

    '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:, (*36)

   'locale_separator' => '_',

What applies for the fallback of the locales using the en-MX format?, (*37)

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., (*38)

Translation Autoloading

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:, (*39)

  • enableAutoloadTranslations() - forces to load all translations
  • disableAutoloadTranslations() - disables autoload and returns parent attributes
  • defaultAutoloadTranslations() - does not change the default behavior logic (default)

Add ons

Thanks to the community a few packages have been written to make usage of Translatable easier when working with forms:, (*40)

FAQ

I need some example code!

Examples for all the package features can be found in the code used for the tests., (*41)

I need help!

Got any question or suggestion? Feel free to open an Issue., (*42)

I want to help!

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, (*43)

Also buy me a beer by making a donation. ❤️, (*44)

I am getting collisions with other trait methods!

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., (*45)

How do I migrate my existing table to use laravel-translatable?

Please see the installation steps to understand how your database should be structured., (*46)

If your properties are written in english, we recommend using these commands in your migrations:, (*47)

// 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');
}); 

How do I sort by translations?

A tip here is to make the MySQL query first and then do the Eloquent one., (*48)

To fetch a list of records ordered by a translated field, you can do this:, (*49)

SELECT * from countries
JOIN country_translations as t on t.country_id = countries.id 
WHERE locale = 'en'
GROUP BY countries.id
ORDER BY t.name desc

The corresponding eloquent query would be:, (*50)

Country::join('country_translations as t', function ($join) {
        $join->on('countries.id', '=', 't.country_id')
            ->where('t.locale', '=', 'en');
    }) 
    ->groupBy('countries.id')
    ->orderBy('t.name', 'desc')
    ->with('translations')
    ->get();

How can I select a country by a translated field?

For example, let's image we want to find the Country having a CountryTranslation name equal to 'Portugal'., (*51)

Country::whereHas('translations', function ($query) {
    $query->where('locale', 'en')
    ->where('name', 'Portugal');
})->first();

You can find more info at the Laravel Querying Relations docs., (*52)

Why do I get a mysql error while running the migrations?

If you see the following mysql error:, (*53)

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'my_database.#sql-455_63'
  (errno: 150) (SQL: alter table `country_translations` 
  add constraint country_translations_country_id_foreign foreign key (`country_id`) 
  references `countries` (`id`) on delete cascade)

Then your tables have the MyISAM engine which doesn't allow foreign key constraints. MyISAM was the default engine for mysql versions older than 5.5. Since version 5.5, tables are created using the InnoDB storage engine by default., (*54)

How to fix

For tables already created in production, update your migrations to change the engine of the table before adding the foreign key constraint., (*55)

public function up()
{
    DB::statement('ALTER TABLE countries ENGINE=InnoDB');
}

public function down()
{
    DB::statement('ALTER TABLE countries ENGINE=MyISAM');
}

For new tables, a quick solution is to set the storage engine in the migration:, (*56)

Schema::create('language_translations', function(Blueprint $table){
  $table->engine = 'InnoDB';
  $table->increments('id');
    // ...
});

The best solution though would be to update your mysql version. And always make sure you have the same version both in development and production environment!, (*57)

Donations

This software has been crafted with attention and love., (*58)

Show your love and support by sending bitcoin to this address: 167QC4XQ3acgbwVYWAdmS81jARCcVTWBXU, (*59)

Or by sending to this PayPal address: ds@dimsav.com, (*60)

❤️ Thank you!, (*61)

The Versions

25/07 2018

dev-issue-309

dev-issue-309

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

25/07 2018

dev-master

9999999-dev

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

25/07 2018

dev-pr-468

dev-pr-468

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

24/07 2018

dev-pr-466

dev-pr-466

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

24/07 2018

dev-pr-453

dev-pr-453

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

24/07 2018

dev-pr-484

dev-pr-484

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

24/07 2018

dev-pr-496

dev-pr-496

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

24/07 2018

dev-next-release

dev-next-release

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

24/07 2018

dev-circleci

dev-circleci

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

10/02 2018

v9.0

9.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

04/01 2018

v8.1

8.1.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

01/09 2017

v8.0

8.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

18/06 2017

v7.3

7.3.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

07/06 2017

v7.2.1

7.2.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

07/06 2017

v7.2

7.2.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

06/06 2017

v7.1

7.1.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

29/01 2017

v7.0

7.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

29/01 2017

dev-circle-ci

dev-circle-ci

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

25/01 2017

v6.1

6.1.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

19/08 2016

v6.0.1

6.0.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

17/08 2016

v6.0

6.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

17/08 2016

v5.6.1

5.6.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

22/04 2016

v5.6

5.6.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

10/04 2016

v5.5.1

5.5.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

19/01 2016

v5.5

5.5.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

15/11 2015

v5.4

5.4.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

23/10 2015

v5.3

5.3.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

18/10 2015

v5.2

5.2.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

17/10 2015

v5.1.2

5.1.2.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

13/09 2015

v5.1.1

5.1.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

07/05 2015

v5.1

5.1.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

27/03 2015

dev-next-major

dev-next-major

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

06/03 2015

v5.0.1

5.0.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

13/02 2015

v5.0

5.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

30/01 2015

v4.5

4.5.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

16/12 2014

v4.4

4.4.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

05/11 2014

v4.3.2

4.3.2.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

04/09 2014

v4.3.1

4.3.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

21/08 2014

v4.3

4.3.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

20/06 2014

v4.2.1

4.2.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

20/06 2014

v4.2

4.2.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

20/06 2014

v4.1.1

4.1.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

10/06 2014

v4.1

4.1.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

02/06 2014

v4.0.1

4.0.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

22/05 2014

v4.0.0

4.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

09/03 2014

v3.0.1

3.0.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

09/03 2014

v3.0.0

3.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

12/02 2014

v2.0.0

2.0.0.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation

11/02 2014

v1.0.1

1.0.1.0

A Laravel package for multilingual models

  Sources   Download

MIT

The Requires

 

The Development Requires

database laravel language translation