Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 844
Nishal Gurung Avatar asked Oct 17 '15 02:10

Nishal Gurung


4 Answers

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

like image 72
tomstig Avatar answered Nov 20 '22 22:11

tomstig


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.

like image 37
Sandyandi N. dela Cruz Avatar answered Nov 20 '22 23:11

Sandyandi N. dela Cruz


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');
like image 9
Inigo Avatar answered Nov 20 '22 21:11

Inigo


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');
like image 1
Cristiano Décio Finato Avatar answered Nov 20 '22 21:11

Cristiano Décio Finato