Laravel 5.4 proper way to store Locale setLocale()

Viewed 32155

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

5 Answers

You could create a middleware like below.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (auth()->check() && $languageId = auth()->user()->language_id) {
            $locale = Language::find($languageId)->locale;
            app()->setLocale($locale);
        }
        
        if ($request->lang) {
            app()->setLocale($request->lang);
        }

        return $next($request);
    }
}


I was facing the same problem, the locale was changing in session but not in config. So have checked the session's locale in every blade and controller and set the default the language instant from there, here is the code on my blade file

@php
if(\Session::get('locale') == 'en') 
    \App::setLocale('en');
else                                
    \App::setLocale('bn');

@endphp

Hope it will help you

Related