PHP 购物车与 Laravel - 数量问题

标签 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 以匹配 array-products id。我尝试 json_decode() 看看这是否会将其放入数组中,但我在这里可能是错的,因为当我返回值时,它是相同的“对象”。例如,购物车中的单个产品可能如下所示:

    [{"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"
}]

最佳答案

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

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

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

或者您可以在 Blade View 中使用它。

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

我建议您在对象中添加数量,然后您可以更新数量并计算价格。

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();
}

希望这有效!

关于PHP 购物车与 Laravel - 数量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37480817/

相关文章:

javascript - Laravel Ajax - 未捕获的 ReferenceError : KWS1389776 is not defined at HTMLButtonElement. onclick

javascript - 是否接受PayPal购物车?

php - Codeigniter 购物车 : Adding the Same Product Again

php - 如何使 php 真正与 https 站点一起工作?

php - Laravel 集合键修改

javascript - 仅从下拉列表中获取选定的值并从下拉列表中删除未选定的值

php - while 在电子邮件中循环 (PHP)

php - 如何编写类似查询的codeigniter

php - Electron 应用程序显示子进程错误,它不起作用

javascript - 加载ajax后如何清除url中的#?