Laravel Magazine
Atomic Updates with Eloquent's increment() and decrement() Methods

Atomic Updates with Eloquent's increment() and decrement() Methods

Eric Van Johnson ·

Every PHP Architect developer has written this at least once:

$product = Product::find($id);
$product->view_count = $product->view_count + 1;
$product->save();

It looks harmless. It also has a race condition baked in. Two requests read the same view_count, both add one, both save, and you've lost an increment. Under real traffic this isn't a hypothetical — it's a slow, silent data corruption bug that shows up as "why is our counter always a little low."

Let the database do the math

Eloquent has had increment() and decrement() for years, and they don't get nearly enough use:

$product->increment('view_count');
$product->decrement('stock', 3);

These don't run a SELECT followed by an UPDATE. They generate a single UPDATE ... SET view_count = view_count + 1 statement. The database performs the arithmetic against whatever the current row value is at the moment the query runs, so two concurrent requests both land correctly instead of racing each other.

Updating other columns at the same time

Both methods accept a second parameter for additional columns to update in the same query — useful for touching a last_viewed_at timestamp alongside a counter:

$product->increment('view_count', 1, [
    'last_viewed_at' => now(),
]);

Bulk increments without loading models

You don't need a model instance at all. The query builder supports the same pattern for bulk updates:

Product::where('category_id', $categoryId)->increment('promo_score', 5);

That single query bumps promo_score by 5 for every matching row, still as one atomic UPDATE.

Watch out for events

increment() and decrement() fire updating/updated events, but they don't run the usual attribute casting and dirty-tracking against the in-memory model the way a full save() call does. If your application logic depends on the model instance reflecting the new value, call refresh() afterward:

$product->increment('stock', -2);
$product->refresh();

When not to use it

If your business logic needs to enforce an invariant — like never letting stock go below zero — a raw increment isn't enough on its own. You'll want that check enforced with a database constraint, a conditional update (WHERE stock >= 3), or a pessimistic lock. But for counters, tallies, and scores where "always correct" matters more than "however we get there," increment() and decrement() are the right tool, and they're already sitting in your Eloquent models today.

Stay Updated

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.