Set Laravel User Locale in Middleware

To set the global Laravel language (locale), you need to use the app()->setLocale() method. But the question is: where to put this method if you want to set the locale based on a DB field like users.language?

Such global settings are often put in the AppServiceProvider, but in this case, it wouldn't work, because you don't have access to Auth:::user() there, you would get an error "Attempt to read property on null":

The reason is that at the time of loading the AppServiceProvider, the session isn't initialized yet, and the User object doesn't exist.

That's why we need to use Middleware.

php artisan make:middleware SetLocale

Then, in the Middleware, you can set the locale from the $request->user() or auth()->user():

app/Http/Middleware/SetLocale.php

class SetLocale
{
public function handle($request, Closure $next)
{
if(! $request->user()) {
return $next($request);
}
 
$language = $request->user()->language;
 
if (isset($language)) {
app()->setLocale($language);
}
 
return $next($request);
}
}

And then you have 2 options to use that Middleware:


Adding Middleware to Global Middleware Stack

app/Http/Kernel.php

// ...
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\SetLocale::class,
],
];

This way, the locale will be set for all routes which are in the web middleware group, which means all routes in the routes/web.php file.


Adding Middleware to Specific Route(s)

app/Http/Kernel.php

protected $middlewareAliases = [
// ...
 
'setLocale' => \App\Http\Middleware\SetLocale::class,
];

And then in your routes file add it to the routes or route groups:

Route::group(['middleware' => ['auth', 'setLocale']], function () {
// ...
});

This way, only specific routes will have the locale set.

avatar

Hi there greate little post and defently usful.

I wanted to like or bookmark it in my profile for future when needed. Is there similiar functionality or are you thinking of adding one ?

πŸ‘ 1
avatar

I've been recommending people to use Browser bookmark feature, but since you are not the first asking for it, I guess we are "forced" to build our own "My bookmarks" :)

Adding to the to-do list.

avatar

That would be awesome @Povilas, the amount of valuable content you guys put out is amazing, and getting it lost inside a browser bookmarks is seriously a shame. I asked for this on Discord sometime back, and i recieved the same response 'browser bookmark' from one of LD team members as well.

This feature would be invaluable, and most welcomed

avatar

Nice post, thanks!

πŸ‘ 1

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials