updateOrCreate with increment in laravel

Nishal Gurung picture Nishal Gurung · Oct 17, 2015 · Viewed 8.8k times · Source

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!

Answer

tomstig picture tomstig · Apr 22, 2019

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