Home:ALL Converter>Update multiple rows of database in Laravel

Update multiple rows of database in Laravel

Ask Time:2015-02-16T18:33:05         Author:Hamid Zamani

Json Formatter

I want a code for update multiple rows of database, somthing like this:

UPDATE values SET data='{"options":["male","female"],"default":"male"}' where project_id=1 and id=1;
UPDATE values SET data='{"options":["male","female"],"default":"male"}' where project_id=1 and id=2;
UPDATE values SET data='{"options":["male","female"],"default":"male"}' where project_id=1 and id=3;

After some hours i could get result with something like this in laravel framework:

$values = Value::where('project_id', $id)->get();
$sql = "";
foreach($request->fields as $field) {
  if(!empty($field->default)) { //New default value is set
    foreach($values as $value) {
      $data = json_decode($value->data, true); /**data column as json object in mysql database **/
      $data["default"] = $field->default;
      $data = json_encode($data);
      $sql .= "update ".DB::connection()->getDatabaseName().".values set data='".$data."' where id="."$value->id;";
    }
  }
}
DB::unprepared($sql);

but this code is not a good practice! So my question is

Is there any ORM way to do this better?!

Author:Hamid Zamani,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/28539400/update-multiple-rows-of-database-in-laravel
Vishal Tarkar :

Here is an easy way to do it.\n\n$values = Value::where('project_id', $id)->update(['data'=>$data]);\n\n\nI found it from this link\n\nHope it helps.",
2016-04-05T10:46:57
yy