darryldecode / laravelshoppingcart

Shopping Cart Implementation for Laravel Framework
1.34k stars 438 forks source link

Adds a product to the cart, but on the next request the cart is empty. #314

Open nechukhaeva opened 3 years ago

nechukhaeva commented 3 years ago

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();
}
nechukhaeva commented 3 years ago

$ cart_id is always the same.

arslanovdev commented 2 years ago

Add \Illuminate\Session\Middleware\StartSession::class to global HTTP middleware stack in Kernel.php

Marre-86 commented 1 year ago

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"...