Increment value of multiple columns at once in Laravel
Laravel comes with handy little utilities when you want to increment or decrement the value of a column in a database table.
For instance, you can use the increment method to increment the value of a column by a given amount.
$user = DB::table('users')->find(1);
// increment the value of the `posts_count` column by 1
$user->increment('posts_count');
// increment the value of the `posts_count` column by 5
$user->increment('posts_count', 5);
Similarly, you can use the decrement method to decrement the value of a column by a given amount.
// decrement the value of the `available_credits` column by 100
$user->decrement('available_credits', 100);
Laravel 9.x comes with two new methods in the Illuminate\Database\Query\Builder class that can help you increment or decrement the value of multiple columns in a single query.
The incrementEach method
The incrementEach method allows you to increment the value of multiple columns in a single query.
DB::table('users')
->where('id', 1)
->incrementEach([
'posts_count' => 1,
'comments_count' => 1
], ['updated_at' => now()]);
As you can see, you can pass an array of columns and their values to the incrementEach method. The first argument is an array of columns and their values and the second argument is an array of columns and their values that you want to update.
The decrementEach method
Similarly, the decrementEach method allows you to decrement the value of multiple columns in a single query.
DB::table('users')
->where('id', 1)
->decrementEach([
'available_credit' => 100,
'reward_points' => 5
], ['updated_at' => now()]);
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!