phplaravelsessionlaravel-5.4

laravel removing item from session


I am using sessions to store cart items. I am able to modify session items but having trouble in removing them. This is the function I'm stuck on

public function removecartitems(Request $request)
{
    $id = $request->input('id');

    $items = Session::get('cart.items', []);

    foreach ($items as &$item) {
        if ($item['id'] == $id) {
            unset($item);
        }
    }

    //Session::set('cart.items', $items);
    $request->session()->put('cart.items', $items);

    return 'removed';
}

This is How i add items in session

$Item = array("id"=>"$productid", "name"=>"$name", "qty"=>"$qty", "rate"=>"$rate", "preview"=>"$preview", "front"=>"$front", "back"=>"$back");



    $request->session()->push('cart.items', $Item);

Solution

  • Firstly, just an FYI, you don't need to wrap your variables in " ".

    I would suggest changing your logic for adding items to the cart from using push() to put() and to also use the product id:

    $item = [
        "id"      => $productid,
        "name"    => $name,
        "qty"     => $qty,
        "rate"    => $rate,
        "preview" => $preview,
        "front"   => $front,
        "back"    => $back,
    ];
    
    $request->session()->put('cart.items.' . $item['id'], $item);
    

    Then your remove method would look something like:

    public function removecartitems(Request $request)
    {
        $request->session()->forget('cart.items.' . $request->input('id'));
    
        return 'removed';
    }