You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向数组添加值不覆盖且可访问,Laravel购物车加商品不重复增数量实现

当前代码的问题是每次调用put方法时直接给cart赋值新数组,覆盖了session中之前存储的购物车数据,未先读取已有内容做增量更新。

修正后的实现代码
public function addToCart(Request $request)
{
    $id = $request->product_id;
    $product = Product::find($id);
    // 先从session读取已有购物车,不存在则初始化空数组
    $cart = $request->session()->get('cart', []);
    
    // 标记商品是否已存在于购物车
    $productExists = false;
    foreach ($cart as &$item) {
        if ($item['id'] == $product->id) {
            // 同款商品数量+1
            $item['quantity']++;
            $productExists = true;
            break;
        }
    }
    // 遍历完成后取消引用,避免后续逻辑出错
    unset($item);
    
    // 购物车无该商品则新增条目
    if (!$productExists) {
        $cart[] = [
            "id" => $product->id,
            "name" => $product->name,
            "price" => $product->price,
            "image" => $product->image,
            "quantity" => 1,
        ];
    }
    
    // 把更新后的购物车存回session
    $request->session()->put('cart', $cart);
    
    dd($cart);
    return redirect('cart');
}
购物车单个商品访问方法
  • 先读取购物车数组:$cart = $request->session()->get('cart', []);,不需要使用only方法,only会返回多套了一层关联结构的数组,直接用get就能拿到存储所有商品的一维数组
  • 遍历访问所有商品:
foreach ($cart as $item) {
    // 直接通过键名访问单个商品的属性
    echo $item['id']; // 商品ID
    echo $item['name']; // 商品名称
    echo $item['quantity']; // 商品购买数量
}
  • 按商品ID查找指定商品:
$targetProductId = 1;
// 集合写法
$targetItem = collect($cart)->firstWhere('id', $targetProductId);

// 原生数组写法
$targetItem = null;
foreach ($cart as $item) {
    if ($item['id'] == $targetProductId) {
        $targetItem = $item;
        break;
    }
}

内容的提问来源于stack exchange,提问作者Scotty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:36:03