What I am trying to do is to update or insert the row in table. In my case, update looks something like this:
\DB::table('inventories')->where('product_code',$product_code)->increment('stock_current_quantity',$quantity);
I don't want to use if else statement. What I actually want is to integrate increment into following statement so it update as above statement.
\App\Inventory::updateOrCreate(['product_code' => $product_code], ['stock_current_quantity'=>$quantity]);
Thanks in advance!
Because google brought me here and I think the answers here, especially when you simply want to use updateOrCreate, are not as satisfying as this:
\App\Inventory::updateOrCreate([
'product_code' => $product_code
],
[
'stock_current_quantity' => \DB::raw('stock_current_quantity + 1')
]
);
Credits to this guy
Why not do:
$inventory = \App\Inventory::firstOrNew(['product_code' => $product_code]);
$inventory->stock_current_quantity = ($inventory->stock_current_quantity + $quantity);
$inventory->save();
If the model doesn't exists, $inventory->stock_current_quantity
will only be equal to $quantity
, else, it will increment it by $quantity
.
I am using Laravel 7.8.1 and rolling it all into one statement as per the following works fine:
$user->league_entries()->updateOrCreate([
'month' => $month,
'year' => $year
])->increment('score');
just contributing if someone else has this problem
it doesn't exist, creates, but with zero
self::firstOrNew(['product_code' => $product_code]);
then, increment it... if other process updates it to 1 before me (in this middle time between firstOrNew and increment), this will update to 2, avoiding losing the prior update
self::where('product_code', $product_code)->increment('stock_current_quantity');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With