R
R
Roman Volkov2016-01-30 19:30:37
Internationalization and localization
Roman Volkov, 2016-01-30 19:30:37

How to properly implement database localization in laravel?

There is a site, on Laravel 5.2. Articles are published on the site. Articles are taken from the database. Here also it would be desirable, that for each language (Russian, English, German) fields with the necessary text were pulled up. How it is better to implement it? Maybe there are some libraries?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrzej Wielski, 2016-01-30
@white_wolf_17

In my opinion, the use of packages for this purpose is impractical.
The usual polymorphic relationship will do.
And so, let's imagine that the main content of the article is in Russian.
First, let's create a model of our localization:
We indicate that this is a polymorphic relationship:

protected $table = 'localization';

public function lozalizable()
  {
      return $this->morphTo();
  }

In our article model, we will bind the newly created model as a link:
public function lozalization(){
      return $this->morphOne('App\Localization', 'lozalizable');
  }

And create a migration for the Lozalizable model:
Schema::create('localization', function (Blueprint $table) {
        $table->increments('id');
        $table->string('field');
        $table->string('language');
        $table->string('value');
        $table->string('lozalizable_type');
        $table->integer('lozalizable_id');
        $table->timestamps();
      });

Now, to create a localization of an article with the en language, we will execute the following code:
$article = Article::create($Atricle);

$localization = new Localization;
$localization->language = 'en';
$localization->field = 'content';
$localization->value = 'Znachenye na english yazike';
$article->localization()->save($localization); //привязываем к свежесозданному объекту Article новую локализацию

Using the scope functions in the model, you can easily implement a more convenient pulling out of the desired value and language:
public function scopeGetLocalize($language, $field){
     return $this->localization()->where(['language' => $language, 'field' => $field])-> firstOrFail()->value;
}

In this case, say, the title field for localization en can be pulled out like this:
$article->getLocalize('en', 'title')

R
Rikcon, 2016-01-30
@Rikcon

https://github.com/mcamara/laravel-localization
Here is for the locale switching itself (I used it half a year ago).
And so everything is simple, we add the lang field to the table with articles, and in fact we save n different articles (how many languages ​​do you have, I xs), we take the right article from the database.

S
sawa4, 2016-06-23
@sawa4

How to use the standard methods to switch the language and fetch data from the database of the corresponding language?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question