I don't know your exact configuration, as I'm not familiar with this package, but this is my middleware:
public function handle(Request $request, Closure $next): Response
{
if (
isset(auth()->user()->language)
&& auth()->user()->language
&& array_key_exists(auth()->user()->language, Config::get('languages'))
) {
if (session()->has('applocale') && array_key_exists(session()->get('applocale'), config('languages'))) {
App::setLocale(session()->get('applocale'));
} else {
Session::put('applocale', auth()->user()->language);
}
}
if (session()->has('applocale') && array_key_exists(session()->get('applocale'), config('languages'))) {
App::setLocale(session()->get('applocale'));
} else { // This is optional as Laravel will automatically set the fallback language if there is
// none specified
App::setLocale(config('app.fallback_locale'));
}
return $next($request);
}
At the bottom of routes/web.php
Route::get('lang/{lang}', [LanguageController::class, 'switchLang'])->name('lang.switch');
The Controller:
final class LanguageController extends Controller
{
public function switchLang(string $lang): RedirectResponse
{
if (array_key_exists($lang, Config::get('languages'))) {
Session::put('applocale', $lang);
}
return Redirect::back();
}
}