laravel - 无法在控制器构造函数中获取会话

gog*_*ubi 12 php session constructor laravel

在新的laravel中,我无法在构造函数中获取会话.为什么?

public function __construct()
{
    dd(Session::all()); //this is empty array
}
Run Code Online (Sandbox Code Playgroud)

然后在下面

public function index()
{
    dd(Session::all()); //here works
}
Run Code Online (Sandbox Code Playgroud)

在旧的laravel我记得没有这个问题.改变了什么?

Rob*_*sen 33

Laravel 5.3默认情况下不能这样做.但是当你编辑你Kernel.php并改为protected $middleware = [];以下时它会工作.

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',
    ],
];
Run Code Online (Sandbox Code Playgroud)

希望这个有效!


Sam*_*oud 7

作为其他答案,没有开箱即用的解决方案。但是您仍然可以使用中间件在构造函数中访问它。

所以这是另一个技巧

public function __construct(){
    //No session access from constructor work arround
    $this->middleware(function ($request, $next){
        $user_id = session('user_id');
        return $next($request);
    });

}
Run Code Online (Sandbox Code Playgroud)


Ale*_*nin 5

Laravel 5.3中,会话相关功能在控制器构造函数中不起作用,因此您应该将所有与会话相关的逻辑移动到方法中.


Kam*_*esh 5

Laravel 5.7解决方案

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

}
Run Code Online (Sandbox Code Playgroud)

如果要将构造函数用于任何其他功能或查询或数据,请在$ this-> middleware函数中进行所有工作,而不要超出此范围。如果这样做,它将无法在整个类的所有功能中起作用。