Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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()]);
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?