Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel built-in multilang not working correctly

thanks for taking the time to read this
I’m using Laravel 10.7.1
I have the languages folders setup correctly (I hope) in Resources/lang/ – ar/fr/en / messages.php

Here’s the code in app.php

'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),

Here’s the route in web.php

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use App\Http\Controllers\LocaleController;  
Route::get('set-locale/{locale}', [LocaleController::class, 'setLocale'])->name('locale.set');

Here’s my LocaleController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;


class LocaleController extends Controller
{
    public function setLocale($locale)
    {
        session()->put('locale', $locale);
        App::setLocale($locale);
        return redirect()->back();
    }
}

Using these buttons to change the language

    <a href="{{ route('locale.set', 'en') }}">English</a>
    <a href="{{ route('locale.set', 'fr') }}">Français</a>
    <a href="{{ route('locale.set', 'ar') }}">العربية</a>

when I try this code to see what’s going on

<div>Current locale: {{ session()->get('locale') }}</div>
<h1>{{ trans('messages.welcome') }}</h1>

The result is :

Current locale: fr
Welcome

Despite the message being correctly translated.

>Solution :

The signature for the trans helper is the following:

function trans($key = null, $replace = [], $locale = null)

You could pass the locale as the third parameter.

<div>Current locale: {{ session()->get('locale') }}</div>
<h1>{{ trans('messages.welcome', [], session()->get('locale')) }}</h1>

There is another helper that is an alias to trans. __.

<div>Current locale: {{ session()->get('locale') }}</div>
<h1>{{ __('messages.welcome', [], session()->get('locale')) }}</h1>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading