laravel - Can't get session in controller constructor

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!


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.


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);
    });

}