Search code examples
laravellocale

Laravel 5.4 proper way to store Locale setLocale()


I need to know. What is the proper way to store Locale for user. If for each users' request I change the language by

    App::setLocale($newLocale);

Would not it change language for my whole project and for other requests as well? I mean when one user changes language it will be used as default for other users.

Thanks in advance


Solution

  • If you set App::setLocale() in for example in your AppServiceProvider.php, it would change for all the users.

    You could create a middleware for this. Something like:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class SetLocale
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            app()->setLocale($request->user()->getLocale());
    
            return $next($request);
        }
    }
    

    (You need to create a getLocale() method on the User model for this to work.)

    And then in your Kernel.php create a middleware group for auth:

    'auth' => [
        \Illuminate\Auth\Middleware\Authenticate::class,
        \App\Http\Middleware\SetLocale::class,
    ],
    

    And remove the auth from the $routeMiddleware array (in your Kernel.php).

    Now on every route that uses the auth middleware, you will set the Locale of your Laravel application for each user.