laravel - Can't get session in controller constructor

孤人 提交于 2019-12-17 16:06:59

问题


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?


回答1:


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!




回答2:


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

}



回答3:


In Laravel 5.3 sessions related functionality will not work in the a controller constructor, so you should move all sessions related logic to methods.




回答4:


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.




回答5:


 *This one solved mine problem to use session in constructor* 
   $this->middleware(function ($request, $next) {
        if (!session('records_per_page')) {
            session(['records_per_page' => 20]);
        }

        // update rows per page
        if (!empty(\Request::get('records_per_page')) && in_array(\Request::get('records_per_page'), [20, 50, 80, 100])) {
            session(['records_per_page' => \Request::get('records_per_page')]);
        }
        return $next($request);
    });


来源:https://stackoverflow.com/questions/41542802/laravel-cant-get-session-in-controller-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!