laravel - Can't get session in controller constructor

后端 未结 8 1762
感动是毒
感动是毒 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:29

    If anyone is coming across this question in now, instead of accessing session values in controller constructors, I will suggest creating a middleware and placing it in the Web middleware section in the App\Http\Kernel.

    This is because sessions are not part of the requests that are passed to Controller constructors. To then do any session value checks or manipulation in every controller, it is safer to create a middleware.

    This is where session values can be accessed as part of the HTTP request going into the route.

    `/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            ...,
            ...,
            ...,
            ...,
            ...,
            \Illuminate\Session\Middleware\StartSession::class,
            \App\Http\Middleware\MySpecialMiddleWareToAccessSessionVariables::class
        ],
    
        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];`
    

    This is because \Illuminate\Session\Middleware\StartSession has started the session before it hits your routes

提交回复
热议问题