Session Doesnt overwrite Local Lang (Lang Switcher)
I have set up a language switch, but when I change the language, it does change in the session, which is good. However, after refreshing, the local language doesn't change because it's only changed in the session. So, how can I make the {{__('messages.welcome')}} display from the local session?
Blade
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-md-12 text-center mt-5">
// this will return the default on e
{{app()->getLocale()}}
// this will return the right one
{{Session::get('app.locale')}}
// and this takes the default one not the session on
<h3>{{__('messages.welcome')}}</h3>
</div>
</div>
</div>
@endsection
LanguageController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
class LanguageController extends Controller
{
public function switchLang($lang)
{
if (array_key_exists($lang, Config::get('languages'))) {
Session::put('app.locale', $lang);
//dd(Session::get('app.locale'));
}
return redirect('/languageDemo');
}
}
AFAIK you need to pull the setting from session and set the locale for yourself
create a middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class SetLocale
{
/**
* @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)
{
$locale = $request->input('lang');
if ($locale) {
//allowlist just some supported values
if (!in_array($locale, ['en', 'de'])) {
abort(400);
}
app()->setLocale($locale);
Session::put('locale', $locale);
} elseif (Session::has('locale')) {
app()->setLocale(Session::get('locale'));
}
return $next($request);
}
}
register it for your routes. and then just add lang variable to any get route. it then stores it in session and uses it from session (also sets the locale) for following requests. tweak as you wish
__('message.welcome') uses the locale set in config/app. you can change it there or use App::setLocale($locale); to set the locale dynamically per request. You can create a locale field for user model and a locale middleware to set the local for each request per user locale field. Using the same middleware you can also set local based on the session.