Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - Can't get session in controller constructor

Tags:

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?

like image 466
gogagubi Avatar asked Jan 09 '17 07:01

gogagubi


People also ask

How can use session in controller constructor in laravel?

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

Can we use session in laravel API?

Laravel Passport is a token-based authentication package, it does not use sessions!

How can we set session in laravel?

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.

How does session work in laravel?

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.


2 Answers

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!

like image 54
Robin Dirksen Avatar answered Oct 11 '22 04:10

Robin Dirksen


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.

like image 40
Kamlesh Avatar answered Oct 11 '22 03:10

Kamlesh