laravelshoppingcart
laravelshoppingcart copied to clipboard
Adds a product to the cart, but on the next request the cart is empty.
These are my methods for working with the cart. But after I add the product and call the new method, the basket is empty.
public function index() { if(!isset($_COOKIE['cart_id'])) { $_COOKIE['cart_id'] = uniqid(); setcookie('cart_id', uniqid(), 0); } $cart_id = $_COOKIE["cart_id"]; $cart = \Cart::session($cart_id);
$all = $cart->getContent()->toArray();
$all['total_quantity'] = $cart->getTotalQuantity();
$all['total_amount'] = $cart->getTotal();
return json_encode($all);
}
public function add(Request $request)
{
$product = Product::where('id', $request->id)->first();
if(!isset($_COOKIE['cart_id']))
{
$_COOKIE['cart_id'] = uniqid();
setcookie('cart_id', uniqid(), 0);
}
$cart_id = $_COOKIE['cart_id'];
$cart = \Cart::session($cart_id);
$cart->add([
'id' => $product->id,
'name' => $product->name,
'price' => $product->price,
'quantity' => $request->qty,
'attributes' => [
'category_id' => $product->category_id,
'vendor_code' => $product->vendor_code,
'image' => $product->image
]
]);
return $cart->getContent()->toJson();
}
public function update(Request $request){
if(!isset($_COOKIE['cart_id']))
{
$_COOKIE['cart_id'] = uniqid();
setcookie('cart_id', uniqid(), 0);
}
$cart_id = $_COOKIE['cart_id'];
$cart = \Cart::session($cart_id);
if($cart->get($request->id)) {
//на какое количество изменить
$cart->update($request->id, ['quantity' => $request->qty]);
}
return $cart->getContent()->toJson();
}
public function delete(Request $request){
if(!isset($_COOKIE['cart_id']))
{
$_COOKIE['cart_id'] = uniqid();
setcookie('cart_id', uniqid(), 0);
}
$cart_id = $_COOKIE['cart_id'];
$cart = \Cart::session($cart_id);
if($cart->get($request->id)){
$cart->remove($request->id);
}
return $cart->getContent()->toJson();
}
$ cart_id is always the same.
Add \Illuminate\Session\Middleware\StartSession::class to global HTTP middleware stack in Kernel.php
Add \Illuminate\Session\Middleware\StartSession::class to global HTTP middleware stack in Kernel.php
Thank you! It helped to solve the issue for me! I think this info should be in the docks, not in the depths of "issues"...