Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

Eloquent: incrementing columns without update() function

July 20, 2015
1 min read

Tutorial last revisioned on August 18, 2022 with Laravel 9

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?

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

AK
abdalla karam ✓ Link copied!

nice

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.