From 6eb7c0c380532d36bda99a405a9450b7a181b0ee Mon Sep 17 00:00:00 2001 From: Jyrki De Neve Date: Thu, 28 Sep 2023 14:21:03 +0300 Subject: [PATCH] Add is_filament_livewire_route helper and check it in the SetLocale middleware --- src/Http/Middleware/SetLocale.php | 19 ++++++++++++++++++- src/helpers.php | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/Http/Middleware/SetLocale.php b/src/Http/Middleware/SetLocale.php index 6c59080..b9b5790 100644 --- a/src/Http/Middleware/SetLocale.php +++ b/src/Http/Middleware/SetLocale.php @@ -4,7 +4,10 @@ use Closure; use Codedor\LocaleCollection\Facades\LocaleCollection; +use Filament\Facades\Filament; +use Filament\Panel; use Illuminate\Http\Request; +use Illuminate\Support\Str; class SetLocale { @@ -16,7 +19,21 @@ class SetLocale */ public function handle(Request $request, Closure $next) { - LocaleCollection::setCurrent($request->segment(1), $request->root()); + if (is_filament_livewire_route($request)) { + return $next($request); + } + + $locale = $request->segment(1); + + if ($request->headers->has('X-LIVEWIRE')) { + $snapshot = json_decode($request->json('components.0.snapshot', []), true); + + if (isset($snapshot['memo']['locale'])) { + $locale = $snapshot['memo']['locale']; + } + } + + LocaleCollection::setCurrent($locale, $request->root()); return $next($request); } diff --git a/src/helpers.php b/src/helpers.php index 5712d07..a2dff84 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -2,7 +2,10 @@ use Codedor\LocaleCollection\LocaleCollection; use Codedor\TranslatableRoutes\TranslateRoute; +use Filament\Facades\Filament; +use Filament\Panel; use Illuminate\Support\Collection; +use Illuminate\Support\Str; if (! function_exists('translate_route')) { function translate_route(string $routeName, string $locale = null, array|Collection $parameters = []): ?string @@ -17,3 +20,20 @@ function translated_routes(string $routeName = null, array $parameters = [], str return TranslateRoute::getAllForNameOrCurrent($routeName, $parameters, $fallbackRoute); } } + +if (! function_exists('is_filament_livewire_route')) { + function is_filament_livewire_route($request): bool + { + if ($request->headers->has('X-LIVEWIRE') && $request->server('HTTP_REFERER')) { + $referer = $request->server('HTTP_REFERER'); + $isFilament = collect(Filament::getPanels()) + ->contains(fn (Panel $panel) => Str::startsWith($referer, $panel->getUrl())); + + if ($isFilament) { + return true; + } + } + + return false; + } +}