John Davidson

php - Perform addition operation in Laravel updateOrCreate

0 comments
Message:


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



My Answer:
You can try using the `firstOrCreate` method instead of `updateOrCreate` and then manually perform the addition operation on the price field. Here's an example:

php
$cart = Cart::firstOrCreate(
['order_id' => $order->id, 'product_id' => $request->product_id],
['price' => 0]
);

$cart->price += $request->price;
$cart->save();


This way, if the cart model is created for the first time, the price will be set to 0 and then you can manually add the new price to it. If the cart model already exists, the price will be updated accordingly.

Rate this post

5 of 5 based on 9666 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us