Laravel Use DB::Raw with Concat if value not null

Viewed 307

I need to concat values in Laravel Update query.If Id value is 12, and If I need to append 14 to it, it should be 12,14.if ID value is null, then it should append as 14 instead of ,14.I used the following code,

$inscustrec =DB::table('configure')->where('POST_ID', $request->postid)
        ->update(
        [
             'ID' => DB::raw('CONCAT(COALESCE(ID),",'. $insrec.'")')
          ]);

i am getting comma as first character if the ID value is null.

I tried the following code,

$inscustrec =DB::table('configure')->where('POST_ID', $request->postid)
    ->update(
    [
         'ID' => trim(DB::raw('CONCAT(COALESCE(ID),",'. $insrec.'")'),",")
      ]);

But this code not working.

Any help would be greatly appreciated.

1 Answers

Give this a go (not sure on your SQL variant my example is using MySQL):

$inscustrec = DB::table('configure')->where('POST_ID', $request->postid)
->update([
    'ID' => trim(DB::raw('CONCAT_WS(",", COALESCE(ID, "'. $insrec.'"))'))
]);

Hope $insrec does not come from user input as its interpolated directly into SQL.

Related