Concat in eloquent update

Viewed 2637

How I can update multiple objects with CONCAT in a single query?

The following code works, but it is not safe:

Table::whereIn('id', $idArray)->where('user_id', $this->userId)
            ->update([
                'title' => DB::raw('CONCAT(title,'.$form->newPart.')')
            ]);

Another method that I have tried is the following, however it does not work:

Table::whereIn('id', $idArray)->where('user_id', $this->userId)
            ->update([
                'title' => DB::raw('CONCAT(title,?)', [$form->newPart])
            ]);
4 Answers

I came here from a search due to a similar problem. Your question helped me find a solution here it is:

Table::whereIn('id', $idArray)->where('user_id', $userId)
                ->update([
                    'title' => DB::raw("CONCAT(title,'$title')")
                ],$title);

I think you will just have to call the setBindings method.

    Table::whereIn('id', $idArray)->where('user_id', $this->userId)
        ->update([
            'title' => DB::raw('CONCAT(title, ?)')
        ])
        ->setBindings([$form->newPart]);

Try with this.

$word_to_concat = "xxx";

    DB::table('food')
            ->where('id', $id)
            ->update([      'name_of_column' => DB::raw("CONCAT(name_of_column, '".$word_to_concat."')")  ,'state' => 'off'    ]);
$title = 'two ';
$ids = implode(',',[1,2]);
DB::statement("update table set column = 
case when column is null or column ='' then 'one ' 
else concat(column,'$title') end where id in($ids)");
Related