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
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>