简体   繁体   中英

Laravel - How to update array value in laravel session?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM