Skip to content

Instantly share code, notes, and snippets.

@jkoop
Created March 5, 2024 21:23
Show Gist options
  • Save jkoop/369709073351a3c2e95e517f467d51b6 to your computer and use it in GitHub Desktop.
Save jkoop/369709073351a3c2e95e517f467d51b6 to your computer and use it in GitHub Desktop.
Laravel 10; set App and User's locale based on browser's preferred language and server's `lang/` directory; @requires `punic/punic`
<?php
/**
* For Laravel 10.
* Automatically set App and User's locale based on browser's preferred
* language and server's `lang/` directory.
* @copyright 2024 Joe Koop
* @license MIT
*/
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Punic\Misc as PunicMisc;
use Symfony\Component\HttpFoundation\Response;
class SetLocale {
public function handle(Request $request, Closure $next): Response {
$availableLocales = [];
foreach (glob(base_path("lang/*")) as $path) {
$name = Str::of(basename($path))->explode(".")->first();
if (Str::startsWith($name, "php_")) continue; // laravel-vue-i18n
$availableLocales[] = $name;
}
$acceptLanguages = PunicMisc::parseHttpAcceptLanguage($request->header("Accept-Language"));
$locale = config("app.locale");
foreach ($acceptLanguages as $language => $q) {
if (in_array($language, $availableLocales)) {
$locale = $language;
break;
}
}
App::setLocale($locale);
/** @var ?User */
$user = Auth::user();
if ($user != null and $user->locale != $locale) {
$user->locale = $locale;
$user->save();
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment