In new laravel I can\'t get session in constructor. Why?
public function __construct()
{
dd(Session::all()); //this is empty array
}
a
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!
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);
});
}