Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set every row to the same value with Laravel's Eloquent/Fluent?

I need to update all of the rows in a database so that a particular field in all of them is equal to a single value. Here's an example.

Let's say my database table is like so:

id data confirmed
1 someData 0
2 someData 1
3 someData 0

I want to perform a query that sets the confirmed field of every row to 1.

I could do it this way:

$rows = MyModel::where('confirmed', '=', '0')->get();
foreach($rows as $row) {
    $row->confirmed = 0;
    $row->save();
}

But it seems like there would be a better way? A single query that would just say "set every row's 'confirmed' field to 1."

Does such a query exist in Laravel's Eloquent/Fluent?

like image 987
Pete Avatar asked Mar 25 '13 19:03

Pete


5 Answers

Just to keep this thread current, you can update all rows against an Eloquent model directly using:

Model::query()->update(['confirmed' => 1]);
like image 179
Matt Avatar answered Oct 23 '22 05:10

Matt


Well, an easy answer: no, you can't with eloquent. A model represents 1 row in the database, it wouldn't make sense if they implemented this.

However, there is a way to do this with fluent:

$affected = DB::table('table')->update(array('confirmed' => 1));

or even better

$affected = DB::table('table')->where('confirmed', '=', 0)->update(array('confirmed' => 1));
like image 99
LHolleman Avatar answered Oct 23 '22 04:10

LHolleman


You can do this with elquent (laravel 4):

MyModel::where('confirmed', '=', 0)->update(['confirmed' => 1])
like image 27
styryl Avatar answered Oct 23 '22 04:10

styryl


Solution for updating all rows :

  1. Create an extra column ( like 'updateAll') and assign static value for all rows (like this 'updateAll' = '1' ) in mysql table.

  2. Add hidden input field with name="forUpdateAll" and value="forUpdateAllValue" ( to execute only specific code for updating all rows)

  3. Then for update(Request $request, $id) method add this code :
public function update(Request $request, $id){
      if($request->get('forUpdateAll') == "forUpdateAllValue"){
                 $question = \App\YourModel::where('updateAll',$id)
                     ->update([
                         'confirmed' => 1
                     ]);

      }else {
          //other code ( update for unique record ) 
      }
 }
  1. Setup your form like this :
<form role="form" action="/examples/1" method="post">        
      {{ method_field('PATCH') }}
      {{ csrf_field()}}
      <input type="hidden" name="forUpdateAll" value="forUpdateAllValue">  
      <button type="submit" class="btn btn-primary">Submit</button>
  </form>
like image 1
Ihtisham Hussain Avatar answered Oct 23 '22 04:10

Ihtisham Hussain


Model::where('confirmed', 0)->update(['confirmed' => 1])

like image 1
Faran Avatar answered Oct 23 '22 05:10

Faran