【问题标题】:PHP shopping cart with laravel - quantity issue带有 laravel 的 PHP 购物车 - 数量问题
【发布时间】:2016-09-25 15:16:15
【问题描述】:

我正在处理一个 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() 来查看它是否会使其成为一个数组,但我在这里可能是错的,因为当我返回值时它是同一个“对象”。例如,购物车中的单个产品可能如下所示:

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

【问题讨论】:

    标签: php laravel shopping-cart


    【解决方案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();
    }
    

    希望这行得通!

    【讨论】:

    • 非常感谢您!我想投票,但我需要 15 声望。但再次感谢! :)
    • 没问题,伙计!也许你在几天内就有 15 名声望(还有 2 名)!为它工作!
    • 但其实我遇到了一个小问题。出现错误“未定义的变量 $found”,我尝试自己修复它,但没有技能。
    • 如果你使用 if(!isset($found) && $found !== true) ,它将检查变量是否存在
    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多