简体   繁体   中英

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

I think you can try this :

if($request->session()->has('cart.items') && $request->session()->get('cart.items') != '') {

  $request->session()->forget('cart.items.name');

}

Hope this work for you !!!

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

Hope this helps!

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