Alex Harris
Alex Harris

Reputation: 6392

How to increment and update column in one eloquent query

Is it possible to update a timestamp (besides updated_at) and increment a column in one query? I obviously can

->increment('count')

and separately

->update(['last_count_increased_at' => Carbon::now()])

but is there an easy way to do both together.

Product::where('product_id', $product->id)
    ->update(['count'=> $count + 1, 'last_count_increased_at' => Carbon::now()];

Without having to query and get the count first?

Upvotes: 38

Views: 67954

Answers (3)

Ali Sharifi Neyestani
Ali Sharifi Neyestani

Reputation: 4388

You can specify additional columns to update during the increment or decrement operation:

Product::where('id',$id)
->increment('count', 1, ['increased_at' => Carbon::now()]);

It is more eloquent solution.

Upvotes: 75

madsem
madsem

Reputation: 81

With Laravel 8 you can now achieve this in a single query to create or update on duplicate key.

$values = [
    'name' => 'Something',
    'count' => 1,
];
$uniqueBy = ['name'];
$update = ['count' => DB::raw('count+1')];

Model::upsert($values, $uniqueBy, $update);

If the model exists count will be incremented, if it is inserted count will equal 1. This is done on the DB level, so only one query involved.

Read more about upserts: https://laravel.com/docs/8.x/eloquent#upserts

Upvotes: 7

aynber
aynber

Reputation: 23011

You can use the DB::raw method:

Product::where('product_id', $product->id)
    ->update([
      'count'=> DB::raw('count+1'), 
      'last_count_increased_at' => Carbon::now()
    ]);

Upvotes: 69

Related Questions