Answer the question
In order to leave comments, you need to log in
How to display a multilingual menu?
Good day to all
I'm trying to make a multilingual site. I figured out the switching of languages, plugging in the output of data from the database, so far only the menu. There is a table with menu items. Fields title_ru and title_ua. There is also a $lang variable, which contains the value of the selected language. To get the menu in the blade template there is a code
<ul>
@foreach($menus as $menu)
<li>
<a href='{{ route($menu->path) }}'>{{ $menu->title_.$lang }}</a>
</li>
@endforeach
</ul>
Answer the question
In order to leave comments, you need to log in
Easiest way:
Slightly harder:
class Menu {
public function getTitile ($lang)
{
return $this->getAttribute('title_' . $lang);
}
}
class Menu {
public function getTitleAttribute()
{
return $this->getAttribute('title_' . app('locale'));
}
}
It's not worth reinventing the wheel - Laravel already has a built-in mechanism for localization, it's better to use it: https://laravel.com/docs/master/localization
It provides very convenient localization features in Blade and in PHP:
// Вар 1 - переводы задаются в JSON /resources/lang/en.json
<a href='{{ route($menu->path) }}'>@lang( $menu->title )</a>
// Вар 2 - переводы задаются по ключам в файле /resources/lang/en/messages.php
<a href='{{ route($menu->path) }}'>@lang( 'messages.menu.' . $menu->path )</a>
// Вар 3
<a href='{{ route($menu->path) }}'>{{ $menu->titleLocalized }}</a>
public function getTitleLocalizedAttribute() {
return __( $this->title );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question