How to set every row to the same value with Laravel's Eloquent/Fluent?
Just to keep this thread current, you can update all rows against an Eloquent model directly using:
Model::query()->update(['confirmed' => 1]);
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));
You can do this with elquent (laravel 4):
MyModel::where('confirmed', '=', 0)->update(['confirmed' => 1])
Solution for updating all rows :
Create an extra column ( like 'updateAll') and assign static value for all rows (like this 'updateAll' = '1' ) in mysql table.
Add hidden input field with name="forUpdateAll" and value="forUpdateAllValue" ( to execute only specific code for updating all rows)
- 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 )
}
}
- 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>