I am configuring a multilanguage app. The user is visiting the app as a guest (I wonder if this is related).
My default language in config/app.php is pt-BR. I created a database table called languages, where I save the languages available for the app.
Languages model
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->string('iso2');
$table->string('name');
$table->string('native');
$table->timestamps();
});
I have a dropdown in the navigation bar where the user can select the language. Then, when the page loads, I get the locale from the session to display as the desired locale/language.
<x-dropdown align="right" width="48">
<x-slot name="trigger">
<button >
<div class="flex">
<x-flag :name="app()->getLocale()" />
</div>
<div class="ml-1">
svg for down array
</div>
</button>
</x-slot>
<x-slot name="content">
@foreach ($languages as $lang)
<x-dropdown-link :href="route('language', $lang->iso2)" >
<x-flag :name="$lang->iso2" />
<span class="ml-2">{{ $lang->native }}</span>
</x-dropdown-link>
@endforeach
</x-slot>
</x-dropdown>
Web route for setting the language:
Route::get('lang/{language:iso2}', [LocalizationController::class, 'index'])->name('language');
When the user select the language, a request is sent to this controller.
LocalizationController.php
public function index(Language $language)
{
session()->put('locale', $language->iso2);
return redirect()->back();
}
And I defined this middleware:
App\Http\Middleware\Localization
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class Localization
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if (session()->has('locale')) {
Carbon::setLocale(session()->get('locale'));
App::setLocale(session()->get('locale'));
}
return $next($request);
}
}
I also registered the middleware in kernel.php
protected $middleware = [
\App\Http\Middleware\Localization::class,
...
];
But when I select a locale other than pt-BR, nothing happens. The locale from the session changes, but when I dd on middleware like
dump("Locale session value in localization middleware: ",session()->get('locale') );
The locale is null, but if I print session()->get('locale') in the view, the locale is the one that I selected in the dropdown, but the app locale is still pt-br. I don't understand why this is happening. Does anyone have a clue?