phplaravelinternationalizationlaravel-blademultilingual

Laravel Blade: How to access string translations of a different locale from the current locale?


I am a newbie to laravel. Please humour me. I am working on a website that can be used in two different languages. I have two files, en.json and te.json, in resources/lang:

// en.json
"language-text": "English"
// te.json
"language-text": "తెలుగు"

I need to make it obvious to the visitors that they can use the website in English and Telugu. So in the header in my blade, I have this bit of code to render the language links:

@foreach ($languages as $language)
    @if ($language->code == app()->getLocale())
        <a href={{url()->current()}}>{{ __('language-text') }}</a>
    @else
        <a href={{
                    str_replace(
                        '/'.app()->getLocale().'/',
                        '/'.$language->code.'/',
                        url()->current()
                    )
                }}>{{ __('language-text') }}</a>
    @endif
@endforeach

Output for the English language version:

<a href="mywebsite.com/en/mypage">English</a>
<a href="mywebsite.com/te/mypage">English</a>

Output for the Telugu language version:

<a href="mywebsite.com/en/mypage">తెలుగు</a>
<a href="mywebsite.com/te/mypage">తెలుగు</a>

Whereas I want it like:

<a href="mywebsite.com/en/mypage">English</a>
<a href="mywebsite.com/te/mypage">తెలుగు</a>

I need to access language-text across locales. Like I need to access language-text from te.json when the current locale is en and vice-versa. My laravel-illiterate-brain tells me that it should be simple enough. I have searched far and wide to no avail. These questions seemed promising but those answers simply flew over my head. Does there exist a simpler solution to this problem?

How do you access the keys in resources/lang/te.json while the locale is en and vice-versa?


Solution

  • You can pass locale as 3-rd parameter to __() function.

    Like this:

    {{ __('language-text', [], 'te') }}
    {{ __('language-text', [], 'en') }}
    

    This is not documented in Laravel docs, but you can check source code here.