29

I would like to perform an UPDATE using Eloquent, that will set column_c value using values of column_a and column_b of the same table. Basically, something like this:

User::where('id', '>', 0)
        ->update(['column_c' => $this->column_a + $this->column_b]);

where $this->column_a and $this->column_b would be the actual values from the current row.

MySQL equivalent:

UPDATE `user` WHERE id > 0 SET column_c = column_a + column_b;

Note: The code above is just an example to show the idea. It's not the actual implementation (which would be creating a DB redundancy).

How do I perform such update in Laravel 5.1? I would really like to avoid a foreach.

lesssugar
  • 15,486
  • 18
  • 65
  • 115

2 Answers2

37

Maybe DB::raw can help. This will allow you to use any standard sql query to combine your data:

User::where('id', '>', 1)
    ->update(['column_c' => DB::raw( CONCAT(column_a, '-', column_b) )]);
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
  • 3
    Of course, I know `DB::raw()`, it's handy, but I find it to be a "workaround" for advanced queries, that are hard to build with Eloquent or Query Builder. It's quite disappointing that something that is so easily done in MySQL (as in my post) is unavailable out-of-the-box in Laravel. Anyway, thanks :) – lesssugar Jun 29 '15 at 14:51
  • 1
    But I guess with Eloquent only there is only the way via querying the data first. As you said `DB::raw()` is something for advanced queries and I would call this already advanced as there are no functions like `concat` in laravel. – Pᴇʜ Jun 29 '15 at 15:00
  • Yeah, you're probably right. I will go with it in the end, I suppose. – lesssugar Jun 29 '15 at 15:01
5

Example:

User::where('id', '>', 0)
    ->update(['column_c' => DB::raw('`column_a` + `column_b`') ]);
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
IFCLS
  • 51
  • 1
  • 1
  • 1
    A little more explanation and not only the code itself would have been nice. ;-) – Alexander Dobernig Jan 24 '21 at 09:25
  • I do not see a major difference from accepted answer, you changed id to 0 from 1 and replaced concat with + but that does not seem to make it a different solution to me. – Ruli Jan 24 '21 at 10:10