使用 Ajax 时如何访问购物车 ID 的会话变量?如何设置属性?
How access session variable for cart id when using Ajax? How setup properties?
laravel 5.3 更新后,开发人员无法访问构造函数中的会话变量。问题是 - 如何使用基于会话购物车 ID 的属性设置 CartController?
举个例子:
class CartController extends Controller
{
public $cartId;
public $cartProducts;
public function __construct()
{
$this->cartId= $this->getCartId();
$this->cartProducts = $this->getCartProducts();
}
public function getCartProducts()
{
return CartProduct::with('product')->where('id_cart', $this->getCartId())->get();
}
public function getCartId()
{
$sessionCartId = Session::get('cartId');
$cookieCartId = Cookie::get('cartId');
if ($cookieCartId) {
$cartId = $cookieCartId;
Session::put('cartId', $cartId);
} elseif ($sessionCartId) {
$cartId = $sessionCartId;
Cookie::queue('cartId', $cartId, 10080);
} else {
$cartId = $this->setNewCart();
}
return $cartId;
}
在此示例中,当我通过 ajax getCartProducts() 调用以获取产品列表时,我需要调用方法 getCartId() 而不是 属性 $this->cartId。这还不错 但是 当我调用更复杂的操作(如删除和刷新表)时,方法 getCartId 将被调用多次,从而导致多次查询。现在,如果我可以访问 属性,我可以在一个查询中获得 cartId。
所以问题是 - 如何解决这个问题?
您可以使用 middleware
闭包访问 __construct
中的 session
数据:
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->cartId = $this->getCartId();
$this->cartProducts = $this->getCartProducts();
return $next($request);
});
}
laravel 5.3 更新后,开发人员无法访问构造函数中的会话变量。问题是 - 如何使用基于会话购物车 ID 的属性设置 CartController?
举个例子:
class CartController extends Controller
{
public $cartId;
public $cartProducts;
public function __construct()
{
$this->cartId= $this->getCartId();
$this->cartProducts = $this->getCartProducts();
}
public function getCartProducts()
{
return CartProduct::with('product')->where('id_cart', $this->getCartId())->get();
}
public function getCartId()
{
$sessionCartId = Session::get('cartId');
$cookieCartId = Cookie::get('cartId');
if ($cookieCartId) {
$cartId = $cookieCartId;
Session::put('cartId', $cartId);
} elseif ($sessionCartId) {
$cartId = $sessionCartId;
Cookie::queue('cartId', $cartId, 10080);
} else {
$cartId = $this->setNewCart();
}
return $cartId;
}
在此示例中,当我通过 ajax getCartProducts() 调用以获取产品列表时,我需要调用方法 getCartId() 而不是 属性 $this->cartId。这还不错 但是 当我调用更复杂的操作(如删除和刷新表)时,方法 getCartId 将被调用多次,从而导致多次查询。现在,如果我可以访问 属性,我可以在一个查询中获得 cartId。
所以问题是 - 如何解决这个问题?
您可以使用 middleware
闭包访问 __construct
中的 session
数据:
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->cartId = $this->getCartId();
$this->cartProducts = $this->getCartProducts();
return $next($request);
});
}