-
Rationale:It's 2024. All projects are global, yet Laravel doesn't include any way to automatically detect client-side locale. In my mind there's no reason to not use this as default behaviour, however I would understand shipping the middleware without registering it, or making it route-specific instead of global. As for other methods for setting locale like URL parameters, for example: And don't get me started on using
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\App;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($locale = $request->header('Accept-Language')) {
App::setLocale($locale);
}
return $next($request);
}
}
->withMiddleware(function (Middleware $middleware) {
$middleware->append(SetLocale::class);
}) |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 9 replies
-
It's not that simple, because the Accept-Language header may contain multiple weighted codes or even invalid codes (never trust client-side provided data). But I like the general idea of standardizing that as a default middleware. |
Beta Was this translation helpful? Give feedback.
-
Luckily, the Symfony request already has a |
Beta Was this translation helpful? Give feedback.
-
Why should all be embedded in Laravel? External libs are not ok for this for example? I see that all people want the framework to solve their problems. To have all they need. :) |
Beta Was this translation helpful? Give feedback.
Luckily, the Symfony request already has a
getLanguages()
method to read that header, and agetPreferredLanguage()
method to find the preferred language. So you really only need to use the existing API that Laravel inherits to configure your application.