Search code examples
laravelmiddlewaremultilingualconstruct

Get Language from construct in laravel


i'm trying to get selected language in my construct to use in any function in that class:

my route:

Route::group(['prefix' => 'admin',  'middleware' => ['AdminMiddleWare','auth','localization']], function(){
     Route::get('/', 'AdminController@index')->name('admin.index');
});

My Middleware:

public function handle($request, Closure $next)
{
    if (Session::has('locale') AND array_key_exists(Session::get('locale'), Config::get('languages'))) {
        App::setLocale(Session::get('locale'));
    }
    else {
        App::setLocale(Config::get('app.locale'));
    }
    return $next($request);
}

My controller :

public  $lang;

public function __construct()
{        
    $this->lang = Language::where('lang','=',app()->getLocale())->first();
}

public function index()
{
    $lang = $this->lang;        
    return $lang;
}

but i'm getting only the default locale;

but if i change the controller to this:

public function index()
{
    $lang = Language::where('lang','=',app()->getLocale())->first();

    return $lang;
}

it will work...

how to get in construct and use it in all functions??


Solution

  • In Laravel, a controller is instantiated before middleware has run. Your controller's constructor is making the query before the middleware has had a chance to check and store the locale value.

    There are multiple ways you can set up to work around this - the important thing is to make the call after middleware runs. One way is to use a getter method on your controller:

    class Controller
    {
        /**
         * @var Language
         */
        private $lang;
    
        public function index()
        {
            $lang = $this->getLang();
    
            // ...
        }
    
        private function getLang()
        {
            if ($this->lang) {
                return $this->lang;
            }
    
            return $this->lang = Language::where('lang','=',app()->getLocale())->first();
        }
    }