Search code examples
phplaravellaravel-query-builder

Laravel query builder mass update - sum current value + another value


I am aware that we can do mass updates with Laravel query builder with it's update() method:

DB::table('my_table')
    ->where('created_at', '>=', '2000-01-01')
    ->update(['column' => 10]);

This would be equivalent to this query:

UPDATE my_table SET column = 10 WHERE created_at >= '2000-01-01' 

What if I wanted to increment that column value by ten, instead of setting a fixed value?

This is what I mean, in SQL:

UPDATE my_table SET column = column + 10 WHERE created_at >= '2000-01-01'

Solution

  • You can simply use Db::raw method:

    DB::table('my_table'
      ->where('created_at', '>=', '2000-01-01')
      ->update([
        'column'=> DB::raw('column+10'), 
      ]);
    

    More informations: https://laravel.com/docs/9.x/queries#raw-expressions

    Other solution, use the increment method (https://laravel.com/docs/9.x/queries#increment-and-decrement):

    DB::table('my_table')
       ->where('created_at', '>=', '2000-01-01')
       ->increment('column', 10);