Answer the question
In order to leave comments, you need to log in
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
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();
}
public function lozalization(){
return $this->morphOne('App\Localization', 'lozalizable');
}
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();
});
$article = Article::create($Atricle);
$localization = new Localization;
$localization->language = 'en';
$localization->field = 'content';
$localization->value = 'Znachenye na english yazike';
$article->localization()->save($localization); //привязываем к свежесозданному объекту Article новую локализацию
public function scopeGetLocalize($language, $field){
return $this->localization()->where(['language' => $language, 'field' => $field])-> firstOrFail()->value;
}
$article->getLocalize('en', 'title')
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question