Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows of database in Laravel

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?!

like image 374
Hamid Zamani Avatar asked Feb 16 '15 10:02

Hamid Zamani


People also ask

How to update multiple records in Laravel?

This function is used to update the multiple records in Laravel. You just need to define what you want to update in first argument but with some unique fields, and in second argument define the which fields are unique for update and in third argument list out the fields which will actually be updated in the database.

What is upsert in Laravel query builder?

The upsert method Laravel 8.x’s query builder comes packed with a method called upsert that will let you insert (multiple) rows that do not exist and update the rows that already exist with the new values. So, for instance, let’s say, you have a table called books and it contains the following records right now.

What is the use of save () method in Laravel?

As the name suggest, the save () method is used to save the records. In this method, first we need to find the record and then we can add additional data into it and then we save the records. Thus, it will update the records in database.

Is it possible to update multiple rows with different update values?

This repository has been archived by the owner. It is now read-only. This could be a great addition for the Query Builder API. There really isn't a way to update multiple rows with different update values with the current api.


1 Answers

Here is an easy way to do it.

$values = Value::where('project_id', $id)->update(['data'=>$data]);

I found it from this link

Hope it helps.

like image 96
Vishal Tarkar Avatar answered Nov 02 '22 17:11

Vishal Tarkar