PHP购物车与laravel - 数量问题

时间:2016-05-27 10:15:29

标签: php laravel shopping-cart

我正在开展laravel购物网站项目,我在购物车中的产品数量存在问题。 我对Laravel来说比较新,所以对我来说事情变得更加复杂...... 问题在于我无法以有效的方式循环(并寻找)类似的产品。

但是当我按下"添加到购物车" - 按钮时,此功能将会运行:

public function cart(Product $product){

    $cart = session()->get('cart');

    // If Cart is empty, add a new array in the session
    if ($cart == []) {
        $cart[] = $product;
        session()->put('cart', $cart);
    }else{
        // else if not empty, loop the cart and look if similar product is in the cart.
        for ($i = 0; $i <= count($cart); $i++) {

            $array_cart = json_decode($cart[$i], true);
            if ($product->id == $array_cart["id"]) {
                    $array_cart["id"] += 1;
            }else{
                $cart[] = $product;
                session()->put('cart', $cart);
            } 
        }
    }

    return back();
}

产品是对象,我不知道如何循环查找产品的ID以匹配数组产品ID。我试过json_decode()看看是否会将它变成一个数组,但我可能在这里错了,因为当我返回值时它是相同的&#34; object&#34;。例如,购物车中的单个产品可能如下所示:

    [{"id": 4,
"name": "HP Desktop",
"description": "Ordinary desktop",
"category": "Desktop",
"price": 1,
"views": 63,
"created_at": "2016-04-11 14:42:58",
"updated_at": "2016-05-27 09:12:59"
}]

1 个答案:

答案 0 :(得分:1)

你需要运行一个foreach循环,这将循环遍历所有对象。

例如,您可以在controller中运行此代码以获取id

foreach($products as $product) {
    dump($product->id);
}

或者您可以在blade view中使用此功能。

@foreach($products as $product)
    dump($product->id);
@endforeach

我建议您在对象中添加quantity,而不是更新quantity并计算价格。

public function cart(Product $product){

    $cart = session()->get('cart');

    // If Cart is empty, add a new array in the session
    if ($cart == []) {
        $cart[] = $product;
        session()->put('cart', $cart);
    }else{
        // else if not empty, loop the cart and look if similar product is in the cart.
        foreach ($cart as $product_item) {
            if ($product->id == $product_item["id"]) {
                    $product_item["quantity"] += 1;
                    $found = true;
            }
        }

        if($found !== true) {
             $cart[] = $product;
             session()->put('cart', $cart);
        }
    }

    return back();
}

希望这有效!

相关问题