Oct 19, 2023
0
Level 4
Prevent Repeat Middleware with Livewire
I have some custom middleware set up that sets the localization based on some priorities. The middleware works as expected... except I can't get it to stop! I tried putting in some logic to flag that the locale was set, but it still fires in my logs. I use Livewire, and every time the form gives feedback it wants to run through this. Here is the middleware class. The specific problem surrounds the logic at "Set Already Run Flag."
class Localization {
private array $validLocales;
public function __construct() {
# Get Active Locales - From Locale Model
$this->validLocales = Locale::getActiveLocales();
}
public function handle(Request $request, Closure $next): Response {
# Set Already Run Flag
if ($request->has('localeSet')) {
# Debug
DebugLog('info', '[MW - Localization] Middleware already run, skipping.', [], 'init');
return $next($request);
}
# Check Session
$locale = $request->session()->get('locale');
if ($locale) {
App::setLocale($locale);
$request->attributes->set('localeSet', true);
DebugLog('info', '[MW - Localization] Locale set from session.', ['locale' => $locale], 'init');
return $next($request);
}
# REDACTED - Redundant to Question
# Default to English
App::setLocale('en');
Session::put('locale', 'en');
$request->attributes->set('localeSet', true);
DebugLog('info', '[MW - Localization] Locale set to default.', ['locale' => 'en'], 'init');
return $next($request);
}
}
And an example of some logs:
[2023-10-19 16:16:21] local.INFO: [MD|QY - Locale] Successfully fetched and cached active locales. {"locales":{"en":{"locale_initials":"en","english_name":"English","native_name":"English"},"zh-CN":{"locale_initials":"zh-CN","english_name":"Mandarin Chinese","native_name":""}}}
[2023-10-19 16:16:21] local.INFO: [MW - Localization] Locale set from session. {"locale":"zh-CN"}
[2023-10-19 16:16:21] local.INFO: Successfully prepared locale menu. {"locales":{"English":"English","":"Mandarin Chinese"},"localeMapping":{"en":"English","zh-CN":"Mandarin Chinese"}}
[2023-10-19 16:16:23] local.INFO: [MW - Localization] Locale set from session. {"locale":"zh-CN"}
[2023-10-19 16:16:23] local.INFO: [MW - Localization] Locale set from session. {"locale":"zh-CN"}
[2023-10-19 16:16:25] local.INFO: [MW - Localization] Locale set from session. {"locale":"zh-CN"}
Thank you!
Please or to participate in this conversation.