简体   繁体   中英

How to delete items one by one if the ID is the same ?

I'm developing shopping cart and when I add items two of the same ID and when I click to delete one of them , then it delets both items. How to delete them one by one ? I'm developing with Laravel.

This is the delete function:

public function delete(Request $request, $id)
{
    $products = session('cart');
    foreach ($products as $key => $value)
    {
        if ($value['id'] == $id)
        {
            unset($products [$key]);
        }
    }

    $request->session()->remove('cart');
    Session::forget('ticket');
    $request->session()->put('cart',$products);

    flash()->success('Prekė buvo sėkmingai pašalinta iš krepšelio.');
    return redirect()->back();
}

Since you don't stop the loop, you will end up unset ing all products with that ID. Do the following:

public function delete(Request $request, $id)
{
    $products = session('cart');
    foreach ($products as $key => $value) {
        if ($value['id'] == $id) {
            unset($products [$key]);
            break;
        }
    }

    $request->session()->remove('cart');
    Session::forget('ticket');
    $request->session()->put('cart',$products);

    flash()->success('Prekė buvo sėkmingai pašalinta iš krepšelio.');
    return redirect()->back();
}

However since you are also adding extra text on items I suggest you be more specific on which one you need to delete:

public function delete(Request $request, $id, $text)
{
    $products = session('cart');
    foreach ($products as $key => $value) {
        if ($value['id'] == $id && $value['text'] == $text) {
            unset($products[$key]);
            break;
        }
    }

    $request->session()->remove('cart');
    Session::forget('ticket');
    $request->session()->put('cart',$products);

    flash()->success('Prekė buvo sėkmingai pašalinta iš krepšelio.');
    return redirect()->back();
}

The second suggestion is just speculation on my part. The idea is your real item $id is composed of the database ID and the text, these 2 should uniquely identify the product.

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