1

I have a session to save cart info in laravel like this:

$item = [
          'id' => 1,
          'product_id' => 11
        ];

$item2 = [
          'id' => 2,
          'product_id' => 22
        ];
        \Session::push('cart', $item); 
        \Session::push('cart', $item2);

Now I want delete an Item in array for $id=1:

foreach(\Session::get('cart') as $cart)
{
    if($id==$cart['id'])
    {
       echo 'done';
       \Session::forget('cart.' . $i);
    }
    $i++;
}

It print done but it can not delete that item in list.

what is my wrong?

also I try \Session::pull('card.id', $id);

EDIT

with dd(\Session::get('cart'))

array:4 [▼
  2 => array:5 [▼
    "id" => 1
    "product_id" => "11"
  ]
  3 => array:5 [▶]
  4 => array:5 [▶]
  5 => array:5 [▶]
]

So I try change the code to this:

foreach(\Session::get('cart') as $key->$cart)
{
    if($id==$cart['id'])
    {
       \Session::forget('cart.' . $key);
    }
}

But It can not delete too

1 Answer 1

1

I'm pretty sure that cart.{$id} is not a session key, as you're only explicitly setting cart, which is an array. This should work for you instead:

$id = 1; // set from request, etc.
$cartSession = session()->get("cart");
foreach($cartSession AS $index => $cart){
  if($index == $id){
    unset($cartSession[$index]);
  }
}
session()->put("cart", $cartSession);

Essentially, you pull the session to a variable (array), loop that and unset where $index matches $id, then set the remaining array back as "cart".

Note: I'm using session() instead of \Session, which is just Facade vs global function; shouldn't make a difference on which you use, unless below a certain Laravel version (< 5.0 I believe)

Sign up to request clarification or add additional context in comments.

2 Comments

with change to this: if($id==$cart['id']), your code works. thanks.
Sorry; disappeared there (software update), was gonna say I probably missed the comparison requirement. But regardless, glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.