Eloquent: incrementing columns without update() function

Eloquent mechanism isn’t limited to just create/update/delete functions – that’s why it’s awesome. One of those helpers come to rescue when you need to increment a column, basically run update X set Y=Y+1 where id = Z – apparently, there’s no need to run update() function for that.

A straightforward way of doing this is get the row, make the calculation and update the row, like this:

$customer = Customer::find($customer_id);
$loyalty_points = $customer->loyalty_points + 1;
$customer->update(['loyalty_points' => $loyalty_points]);

What if I told you it could be done in one line? Let’s meet a function called increment():

Customer::find($customer_id)->increment('loyalty_points');

That’s it – it will actually run update column + 1 under the hood.

And not only that, you can specify a second parameter to this function: the amount of incrementing. The default is 1, but it can be any other number:

Customer::find($customer_id)->increment('loyalty_points', 50);

In addition, of course, you also have a decrement() function:

Customer::find($customer_id)->decrement('loyalty_points', 50);

Again, isn’t Eloquent awesome?

Like our articles?
Check out our Laravel online courses!

4 COMMENTS

  1. It depends on whether you already have the user’s model. Cause else you are basically running two queries: 1) first fetching the user and 2) updating the users counter.

    If you don’t have the user yet, then an single update query is enough.

  2. Both of the methods shown are not atomic and therefore inadvisable. The atomic way to do this in SQL would be to do `UPDATE x SET y = y + 1 WHERE z`. You must use the DAO instead of Eloquent to perform this operation like so:

    “`
    Customer::query()
    ->where(‘id’, $customer_id)
    ->update([
    ‘loyalty_points’ => DB::raw(‘loyalty_points + 1’)
    ]);
    “`

    • Your solution updates the update_at column which is preferred in my case. The following snippit does not update that field. Not sure why ->increment(‘count’); doesn’t increment that column.

      DB::table(‘users_history’)
      ->where(‘term’, ‘=’, $keywords)
      ->where(‘user_id’, ‘=’, $user_id)
      ->increment(‘count’);

LEAVE A REPLY

Please enter your comment!
Please enter your name here