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?
In the upgrade guide of Laravel 5.3 there is an example of how to get session data in a controller constructor. $this->middleware(function ($request, $next) { $this->user = Auth::user(); return $next($request); });
Laravel Passport is a token-based authentication package, it does not use sessions!
The session configuration is stored in config/session. php . Be sure to review the well documented options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for the majority of applications.
Sessions are used to store information about the user across the requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used because it is lightweight. Session can be configured in the file stored at config/session.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With