bezhanSalleh / filament-language-switch

A versatile and user-friendly plugin designed for Filament Panels.
MIT License
210 stars 45 forks source link

Add Laravel event to catch locale change in your own application #61

Closed michaelklopf closed 8 months ago

michaelklopf commented 9 months ago

The package is good to change the language in the browser, but we want to save the users locale in the database. Currently that's not possible.

We introduce a Laravel event that gets dispatched when the locale is changed.

In your own application you can listen for this event and add your own listener that uses the locale string to save it in the database like this:

In the EventServiceProvider

    protected $listen = [
        LocaleChanged::class => [
            UserChangedLocale::class,
        ],
    ];

and in the listener


    public function handle(object $event): void
    {
        Filament::auth()->user()->update(['locale' => $event->locale]);
    }

To load the users locale in your application you can add your own middleware to the panel providers where you set the locale from the database

    public function handle(Request $request, Closure $next): Response
    {
        if (filament()->auth()->check()) {
            app()->setLocale(filament()->auth()->user()->locale);
        }

        return $next($request);
    }
bezhanSalleh commented 8 months ago

thanks