laravel - Can't get session in controller constructor

后端 未结 8 1770
感动是毒
感动是毒 2020-12-05 19:02

In new laravel I can\'t get session in constructor. Why?

public function __construct()
{
    dd(Session::all()); //this is empty array
}

a

8条回答
  •  不知归路
    2020-12-05 19:18

    Laravel 5.7 solution

    public function __construct()
    {
    
    $this->middleware(function ($request, $next) {
    // fetch session and use it in entire class with constructor
    $this->cart_info = session()->get('custom_cart_information');
    
    return $next($request);
    });
    
    }
    

    If you want to use constructor for any other functionality or query or data then do all the work in $this->middleware function, NOT outside of this. If you do so it will not work in all the functions of entire class.

提交回复
热议问题