0

I am developing a shopping cart in laravel in which I want to remove array in the session but it is not working.

I have tried these:

https://www.allphptricks.com/simple-shopping-cart-using-php-and-mysql/
https://laracasts.com/discuss/channels/laravel/remove-array-element-from-session?page=1

but it did not work

foreach($request->session()->get('shopping_cart') as $key => $value){
    if($value['code'] == $request->remove_id){
        $request->session()->forget("shopping_cart.". $request->remove_id);
        break;
    }
}
array:4 [▼
  "fh5hhr34" => array:5 [▼
  "name" => "Wilma Goodman"
  "code" => "fh5hhr34"
  "price" => "412"
  "quantity" => "2"
  "image" => "product_pics/1566372402.jpeg"
   ]
  "ghtzzr" => array:5 [▼
  "name" => "Lillian Hays"
  "code" => "ghtzzr"
  "price" => "187"
  "quantity" => "4"
  "image" => "product_pics/1566372214.jpg"
   ]
 ]
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
oshak
  • 13
  • 1
  • 4
  • What is the array we're looking at? The output of the entire session or the output of only the shopping cart? Please show us the code you ran to produce that output. – waterloomatt Aug 26 '19 at 15:57
  • *"How do I remove array from session in laravel"* Simply [unset()](https://www.php.net/manual/en/function.unset.php) ? – Raymond Nijland Aug 26 '19 at 15:57
  • 2
    Possible duplicate of [How to remove an item from session array in laravel](https://stackoverflow.com/questions/42609844/how-to-remove-an-item-from-session-array-in-laravel) – Raymond Nijland Aug 26 '19 at 15:59
  • @waterloomatt it is the output of the entire session. the code that generated the json is print_r(Session::get('shopping_cart')); – oshak Aug 26 '19 at 16:33
  • I can't see why that wouldn't work. What debugging steps have you taken? Ex. have you verified `$request->remove_id` is what you expect? Does `shopping_cart.fh5hhr34` actually exist in the session? – waterloomatt Aug 26 '19 at 17:43

1 Answers1

0

Try this code:

foreach(session('shopping_cart') as $key => $value){
    if($value['code'] == $request->remove_id){
        session()->forget("shopping_cart.$key");
        break;
    }
}

If still does not work you can try to save the session at the end of the foreach, i.e.:

foreach(session('shopping_cart') as $key => $value){
    //....
}
session()->save();

Please let me know if it works.

dparoli
  • 8,891
  • 1
  • 30
  • 38