laraveleloquentlaravel-5.1illuminate-container

updateOrCreate with increment in laravel


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!


Solution

  • 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.