在构造函数Laravel 5.6中无法访问会话

时间:2018-04-22 18:11:22

标签: php laravel session

我的功能在这里,var_dump返回null

public function __construct() {

var_dump(session('cart'));

$this->cart = session('cart');
$this->payment = session('payment');
$this->coupon = session('coupon');

$this->currency = \App\Setting::where('key','eur_currency')->first()->value;

if (!isset($this->cart["items"])) {
  $cart = ['items' => [],'total' => 0, 'sub_total' => 0,'try' => 0];
  session(['cart' => $cart]);
  $this->cart = session('cart');
} 
....
....
....

如何使用__constructor方法访问会话?

编辑:感谢@devk,我的方法现在正在工作。

public function __construct() {
$this->middleware(function ($request, $next) {
  $this->cart = session('cart');
  $this->payment = session('payment');
  $this->coupon = session('coupon');

  $this->currency = \App\Setting::where('key','eur_currency')->first()->value;

  if (!isset($this->cart["items"])) {
    $cart = ['items' => [],'total' => 0, 'sub_total' => 0,'try' => 0];
    session(['cart' => $cart]);
    $this->cart = session('cart');
  }


  if (!isset($this->coupon["applied"])) {
    $coupon = ['applied' => false,'code' => null,'type' => null, 'value' => null];
    session(['coupon' => $coupon]);
    $this->coupon = session('coupon');
  }

  if (!isset($this->payment["payment_type"])) {
    $payment = ['payment_type' => 'CC', 'invoice_type' => 'PERSONAL',   'invoice' => [ 'fullname' => '','email' => '','company' => '','tax_office' => '','tax_id' => '' ]];
    session(['payment' => $payment]);
    $this->payment = session('payment');
  }

  return $next($request);
});

}

1 个答案:

答案 0 :(得分:1)

从Laravel 5.3开始,您无法再访问控制器构造函数中的会话because middleware has not run yet

会话中间件运行后发生的

You can define a closure(滚动到“构造函数中的会话”)。