From aa2f84d72ccb49c042ca2a51ff3f001f23610a4e Mon Sep 17 00:00:00 2001 From: hackerESQ Date: Fri, 23 Aug 2024 14:24:15 -0500 Subject: [PATCH] auto-detect locale based on browser preferences --- app/Http/Middleware/SetLocale.php | 27 +++++++++++++++++++++++++++ bootstrap/app.php | 3 ++- config/app.php | 1 + 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 app/Http/Middleware/SetLocale.php diff --git a/app/Http/Middleware/SetLocale.php b/app/Http/Middleware/SetLocale.php new file mode 100644 index 0000000..8a8539d --- /dev/null +++ b/app/Http/Middleware/SetLocale.php @@ -0,0 +1,27 @@ +has('locale')) { + session()->put('locale', $request->getPreferredLanguage( + config('app.available_locales') + )); + } + + app()->setLocale(session('locale')); + + return $next($request); + } +} \ No newline at end of file diff --git a/bootstrap/app.php b/bootstrap/app.php index d654276..eb4da3f 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,6 @@ withMiddleware(function (Middleware $middleware) { - // + $middleware->append(SetLocale::class); }) ->withExceptions(function (Exceptions $exceptions) { // diff --git a/config/app.php b/config/app.php index f467267..0597435 100644 --- a/config/app.php +++ b/config/app.php @@ -77,6 +77,7 @@ return [ | set to any locale for which you plan to have translation strings. | */ + 'available_locales' => ['en', 'es'], 'locale' => env('APP_LOCALE', 'en'),