Manage a multilingual database with Laravel

I am creating a backend application in Laravel. The backend must manage a collection of objects that are loaded into the application. Objects must be localized depending on the language of the device.

Is there an easy way to do this in Laravel? Perhaps eloquent or a Laravel plugin? I would not want to write localization myself.

(The built-in localization in Laravel is for the interface only, it does not support Eloquent objects)

+6
source share
4 answers

You will need to write it yourself. First you have to model the database tables to support multilingual content, and then in your model you can say something like:

class Content extends Eloquent { public function scopeEnglish($query) { return $query->where('language', '=', 'en'); } public function scopeSpanish($query) { return $query->where('language', '=', 'es'); } } class Post extends Eloquent { public function content() { return $this->hasMany('Content'); } } 

and then you can use it like:

 $englishContent = Posts::find($id)->content->english()->get(); $spanishContent = Posts::find($id)->content->spanish()->get(); 
+9
source

The Glad To Help answer seems perfect for a multilingual site with many languages. I found out that it is embarrassing to do this when your site has only two / three languages.

What I did consists of two columns for each translatable field. for the title attribute, I have title_en and title_es in the database. After that, in the controller, simply set this method for automatic translation.

 public function getTitleAttribute() { $locale = App::getLocale(); $column = "title_" . $locale; return $this->{$column}; } 

Now when you call Post::find($id)->title , it will automatically get a value for the current language.

Hope this helps. Hooray!

+6
source

I made a similar but more universal

 Schema::create('index', function(Blueprint $table) { $table->increments('id'); $table->string('title_uk'); $table->string('title_ru'); $table->string('title_en'); $table->string('heading_uk'); $table->string('heading_ru'); $table->string('heading_en'); $table->string('photo'); $table->timestamps(); }); 

Model

 public function TextTrans($text) { $locale=App::getLocale(); $column=$text.'_'.$locale; return $this->{$column}; } 

Now I do not write out a specific function for each language version, as well as for each field, and call it all:

$text=Index::find('1'); $text->TextTrans('title'); $text->TextTrans('heading');

+4
source

After @ user1067281's answer, I found a great advanced tutorial for a website with multiple languages.

You should fully verify this: https://medium.com/laravel-4/26cdc75e4810

+1
source

Source: https://habr.com/ru/post/954919/


All Articles