phplaravelsessionconstructor

laravel - Can't get session in controller constructor


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

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

and then below

public function index()
{
    dd(Session::all()); //here works
}

In old laravel i remember there was not this problem. something changed?


Solution

  • 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!