auto-detect locale based on browser preferences

This commit is contained in:
hackerESQ
2024-08-23 14:24:15 -05:00
parent 2a8f7e3b55
commit aa2f84d72c
3 changed files with 30 additions and 1 deletions
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SetLocale
{
/**
* Handle an incoming request.
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (!session()->has('locale')) {
session()->put('locale', $request->getPreferredLanguage(
config('app.available_locales')
));
}
app()->setLocale(session('locale'));
return $next($request);
}
}
+2 -1
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Http\Middleware\SetLocale;
use Illuminate\Foundation\Application; use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Foundation\Configuration\Middleware;
@@ -12,7 +13,7 @@ return Application::configure(basePath: dirname(__DIR__))
health: '/up', health: '/up',
) )
->withMiddleware(function (Middleware $middleware) { ->withMiddleware(function (Middleware $middleware) {
// $middleware->append(SetLocale::class);
}) })
->withExceptions(function (Exceptions $exceptions) { ->withExceptions(function (Exceptions $exceptions) {
// //
+1
View File
@@ -77,6 +77,7 @@ return [
| set to any locale for which you plan to have translation strings. | set to any locale for which you plan to have translation strings.
| |
*/ */
'available_locales' => ['en', 'es'],
'locale' => env('APP_LOCALE', 'en'), 'locale' => env('APP_LOCALE', 'en'),