V
V
Vladimir Kokhan2019-08-21 20:21:05
Laravel
Vladimir Kokhan, 2019-08-21 20:21:05

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>

As a result, I get the menu items ru and ua.
The question is how to correctly write this code - {{ $menu->title_.$lang }}, so that the values ​​of the fields {{ $menu->title_ru }} and {{ $menu->title_ua }} are displayed.
That is, what is the correct way to combine two variables?
Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Sokharev, 2019-08-21
@greabock

Easiest way: Slightly harder:

class Menu {
    public function getTitile ($lang) 
    {
        return $this->getAttribute('title_' . $lang);
    }
}

If it matches the locale:
class Menu {
    public function getTitleAttribute() 
    {
        return $this->getAttribute('title_' . app('locale'));
    }
}

But it is worth noting that multilingual applications are written quite differently.

R
Razgelday, 2019-08-22
@Razgelday

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 question

Ask a Question

731 491 924 answers to any question