Home > Software engineering >  Perform addition operation in Laravel updateOrCreate
Perform addition operation in Laravel updateOrCreate

Time:10-27

i'm working on a ecommerce project and i have an issue in the cart system. so, the user can add product to cart by its price and if the user add the same product again, the price (in the cart) should accumulated. for example, i add an apple to cart for $20, then i add it again for $10, the price should be $30 right now.

i tried to do this

$cart = Cart::updateOrCreate(
            ['order_id' => $order->id, 'product_id' => $request->product_id],
            ['price' => DB::raw("price   $request->price")]
);

it works fine to update price from existing cart model, but the price is always null in database if the new cart model is created. do you guys have any suggestions to fix this problem? thanks

CodePudding user response:

You can use the IFNULL() in your raw query

$cart = Cart::updateOrCreate(
            ['order_id' => $order->id, 'product_id' => $request->product_id],
            ['price' => DB::raw("IFNULL(price, 0)  $request->price")]
);

IFNULL(field, 0) will return 0 if the field is NULL and the value if not.

  • Related