Home > Software engineering >  How to increment quantity of laravel model without creating a copy
How to increment quantity of laravel model without creating a copy

Time:10-04

I'm working on trying to create a cart system in laravel, where selecting an item on a menu will add it as a cart item. If the item already exists on the cart, it should just increase the quantity. I have this almost entirely working, except that the solution I've worked out makes it so that in the case of needing to increment the quantity, it will also recreate the cart item, so that there is one both with and without the incremented quantity. I've put a lot of mental energy into struggling with this, and was hoping someone might be able to help. Here is the relevant code, in the controller for creating the cart item.

$cartItems = Cartitem::all();
if($cartItems->isEmpty()){
    $cartItem = new Cartitem([
        'name' => $request->name,
        'image_url' => $request->image_url,
        'description' => $request->description,
        'price' => $request->price,
        'quantity' => 1
    ]);
    $cartItem->save();
} else {
    forEach($cartItems as $item){
        if($request->name != $item->name){
            $cartItem = new Cartitem([
                'name' => $request->name,
                'image_url' => $request->image_url,
                'description' => $request->description,
                'price' => $request->price,
                'quantity' => 1
            ]);
            $cartItem->save();
        } else {
              $item->quantity;
            $item->save(); 
        }
    }
}  

CodePudding user response:

$oldItem = Cartitem::where('name', $request->name)->first();

if ($oldItem) {
    $oldItem->increment('quantity');
}
else {
    $newItem = new Cartitem([
       'name' => $request->name,
       'image_url' => $request->image_url,
       'description' => $request->description,
       'price' => $request->price,
       'quantity' => 1
    ]);

    $newItem->save();
}
  • Related