dor2p0520 2017-01-25 11:46
浏览 205
已采纳

Laravel - 如何在laravel会话中更新数组值?

I'm creating cart functionality in laravel 5.3. when user add product to cart it's basically create session and add product to that session.

let's start with example on that I'm working.

when user add product to cart I am passing required parameter to controller function and then it's store in session. so my controller function is :

public function add_cart(Request $request){


    $product = [
        'sku' => $request['sku'],
        'price' => $request['price'],
        'quantity' => $request['quantity'],
        'brand_id' => $request['brand_id'],
        'brand_name' => $request['brand_name'],
        'brand_img' => $request['brand_img']
    ];

   // dd($product);
    if($request->session()->has('add_to_cart')){
        $request->session()->push('add_to_cart', $product);
    }else{
        $request->session()->push('add_to_cart', $product);
    }


    return count($request->session()->get('add_to_cart'));

}

so after add product to add_to_cart session my session is look like this :

array:2 [▼
0 => array:6 [▼
"sku" => ""
"price" => " "
"quantity" => "1"
"brand_id" => "14"
"brand_name" => "The Body Shop"
"brand_img" => "http://s3.giftcardsindia.in/2015/06/01/original-556c623c560f5.jpg"
 ]
1 => array:6 [▼
"sku" => "ffs002000"
"price" => "2000"
"quantity" => "1"
"brand_id" => "47"
"brand_name" => "The Four Fountains Spa"
"brand_img" => "http://s3.giftcardsindia.in/2015/06/01/original-556c47b5a27eb.jpg"
]
]

using this I can show all cart product in cart page also done with subtotal , tax and total of payment functionality.

Now problem is if I want to update quantity of brand_id : 14 how can I get array of product from session where brand_id is 14 ? and after geting that product array how to update only quantity value from that array ? or may be we can replace whole product array with new one but how to find that product array from session ?

don't have any idea. I search on laravel documentation but not get any method to solve my problem.

  • 写回答

1条回答 默认 最新

  • dongliu5475 2017-01-25 11:52
    关注

    There is no direct way of doing that, You can crate a simple function to update the session for you..

    Here is an example.

    public function updateQuantityByBrand($brand_id, $quantity){
       $cartItems = session()->get('add_to_cart');
    
       foreach($cartItems as $item){
          if($item["brand_id"] == $brand_id){
              $item["quantity"] = $quantity;
          }
       }
    
       return session("add_to_cart", $cartItems);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置