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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算