Integrating the Language Selector into the User Menu for a Filament Top Bar in PHP
Register a new render hook: Start by registering a new render hook in your panel provider. We will place the selector at the position USER_MENU_PROFILE_AFTER to keep the top bar clean, but you can register it at any other position you prefer.
->renderHook( PanelsRenderHook::USER_MENU_PROFILE_AFTER, fn (): View => view('filament.hooks.lang-switcher'), )
We will use Filament's dropdown component to render the sub-navigation of the language selector. Customize the interface as needed, such as adding flags for different languages.
In your filament.hooks.lang-switcher file:
<div> <x-filament::dropdown maxHeight="250px" placement="left-start" teleport="true" > <x-slot name="trigger"> <div class="p-2 flex items-center justify-start gap-2"> <x-filament::icon icon="heroicon-o-chevron-left" class="mx-1 h-5 w-5 text-gray-500 dark:text-gray-400" /> Select Language </div> </x-slot> <x-filament::dropdown.header class="font-semibold" color="gray" icon="heroicon-o-language" > Select Language </x-filament::dropdown.header> <x-filament::dropdown.list> <x-filament::dropdown.list.item :color="(app()->getLocale() === 'en') ? 'primary' : null" icon="heroicon-o-chevron-right" :href="url('lang/en')" tag="a" > English </x-filament::dropdown.list.item> <x-filament::dropdown.list.item :color="(app()->getLocale() === 'es') ? 'primary' : null" icon="heroicon-o-chevron-right" :href="url('lang/es')" tag="a" > Spanish </x-filament::dropdown.list.item> </x-filament::dropdown.list> </x-filament::dropdown> </div>
Create a simple route to capture the selected language and store it in the session:
Route::get('lang/{lang}', function ($lang) { session()->put('current_lang', $lang); return redirect(url()->previousPath()); });
Define a middleware to tell Laravel to take the language from the session:
class SetLang { public function handle(Request $request, Closure $next): Response { return app(StartSession::class) ->handle($request, function ($request) use ($next) { if (! session()->has('current_lang')) { session()->put('current_lang', 'en'); } app()->setLocale(session('current_lang', 'en')); return $next($request); }); } }
Finally, register the middleware within the Filament panel provider:
->middleware([ //... SetLang::class, ])
Take your time to understand each concept before moving on to the next one.
Practice the examples in your own development environment for better understanding.
Don't hesitate to review the additional resources mentioned in the article.
Page loaded in 25.61 ms