Tuesday, February 8, 2022

[FIXED] How to increment and update column in one eloquent query

Issue

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?


Solution

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.



Answered By - Ali Sharifineyestani

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.