简体   繁体   中英

Explain how to use Session In The Constructor Laravel 5.3

according to laravel docs https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors i can no longer access the session in the construct because the middleware isnt loaded yet , they provided an example that i couldnt understand

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->projects = Auth::user()->projects;

        return $next($request);
    });
}

how do i access my session here inside that function? , an explaination would do

将它放在将处理请求的控制器的__construct()函数中。

The Laravel docs state that you can't access middleware anymore in the constructor, because it hasn't been loaded yet.

By using that specific Closure, you're actually forcing php (and Laravel) to load whatever logic you have in the Closure as middleware. Take a look at the basic controller class provided by Laravel and see if you can connect the dots.

Essentially, you're hacking the framework.

That being said, it's really bad practice and you shouldn't temper with your session in controller's constructors.

 public function __constrcut(){
    //changing language accordding to session
    $this->middleware(function($request,$next){
        app::setLocale(Session::get('locale'));
        return $next($request);
    });

This code used for changing language according to session the version which i use laravel 5.5 Note: you must call the middelware first then use session as the constructor not see session this works for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM