It looks like the issue is that the locale is being set in the session, but it is not being applied to the application for the current request. This is because the locale is set in the session, but the application locale is not being updated accordingly.
To fix this, you need to ensure that the application locale is set based on the session value for every request. You can achieve this by using middleware. Here’s how you can do it:
- Create a middleware to set the locale:
First, create a middleware that will set the application locale based on the session value.
php artisan make:middleware SetLocale
- Update the middleware to set the locale:
Edit the SetLocale middleware located at app/Http/Middleware/SetLocale.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}
return $next($request);
}
}
- Register the middleware:
Register the middleware in app/Http/Kernel.php. Add it to the $middleware array or the $middlewareGroups array, depending on your needs. For example, to add it to the web middleware group:
protected $middlewareGroups = [
'web' => [
// Other middleware
\App\Http\Middleware\SetLocale::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
- Update your routes and views:
Your routes and views seem to be correctly set up. Just ensure that the locale is being set correctly in the session and that the middleware is applied.
Here’s a summary of your web.php and login.blade.php:
web.php:
Route::get('language/{locale}', function ($locale) {
app()->setLocale($locale);
session()->put('locale', $locale);
return redirect()->back();
});
login.blade.php:
@foreach(config('app.available_locales') as $locale_name => $available_locale)
<x-nav-link href="language/{{ $available_locale }}" :active="$available_locale == Session::get('locale')">
{{ $locale_name }}
</x-nav-link>
@endforeach
<br>Session Locale: {{ Session::get('locale') }}
<br>{{ __('x') }}
With these changes, the application should correctly toggle between the languages and display the appropriate translations based on the selected locale.