Ad

How To Unset A Laravel Session Array

- 1 answer

Hi I'm trying to remove a product array inside my cart session when the quantity is 1 and user tries to remove it, simply unsets that.

Here is my code:

public function remove($id)
{
    if (session('cart')) {
        foreach (session('cart') as $product) {
            if ($product['id'] == $id) {
                if ($product['qty'] == 1) {
                
                } else {
                    $product['qty'] = $product['qty'] - 1;
                }
            };
        }

        Session::put('cart', session('cart'));
        
        return redirect()->back();
    }
}

I tried to use Session::forget('cart.'$num) but having some more issues.

Ad

Answer

Take your session edit it, and then re-set it:

$cart = session('cart');
array_forget($cart, $num);
session()->put('cart', $cart);

Ad
source: stackoverflow.com
Ad