laravel - Can't get session in controller constructor

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

    You can't do it by default with Laravel 5.3. But when you edit you Kernel.php and change protected $middleware = []; to the following it wil work.

    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ];
    
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
    

    Hope this works!

    0 讨论(0)
  • 2020-12-05 19:37

    As of other answers no out of the box solution for it. But you still can access it using Middleware in constructor.

    So here is another hack

    public function __construct(){
        //No session access from constructor work arround
        $this->middleware(function ($request, $next){
            $user_id = session('user_id');
            return $next($request);
        });
    
    }
    
    0 讨论(0)
提交回复
热议问题