← Back to all snippets
PHP

Atomically Increment or Decrement Model Attributes

Safely update numeric attributes in Laravel Eloquent models without fear of race conditions using atomic increment/decrement operations.

use App\Models\Post;
use App\Models\User;

// Assuming a Post model with a 'views' column and a User model with a 'balance' column

// Increment a single attribute by 1
$post = Post::find(1);
$post->increment('views'); // Adds 1 to the 'views' column

// Increment an attribute by a specific amount
$post->increment('views', 5); // Adds 5 to the 'views' column

// Decrement a single attribute by 1
$user = User::find(1);
$user->decrement('balance'); // Subtracts 1 from the 'balance' column

// Decrement an attribute by a specific amount
$user->decrement('balance', 10); // Subtracts 10 from the 'balance' column

// Increment and update other columns in a single atomic operation
$post->increment('likes', 1, ['last_liked_at' => now()]);

// Decrement and update other columns
$user->decrement('login_attempts', 1, ['last_attempt_at' => now()]);

echo "Post views after operations: ".$post->fresh()->views."
";
echo "User balance after operations: ".$user->fresh()->balance."
";
How it works: Eloquent's `increment()` and `decrement()` methods provide a convenient and safe way to update numeric attributes in your database. These operations are atomic, meaning they directly modify the value in the database using a single query, which helps prevent race conditions that can occur if you retrieve, modify, and then save the model in separate steps. You can specify the amount to increment/decrement and even pass an array of additional columns to update simultaneously.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs