How can I update multiple fields in an Eloquent model? Let's say I got it like this:
$user = User::where("username", "=", "rok");
And then I have all these model parameters:
$new_user_data = array("email" => "[email protected]", "is_superuser" => 1, ...);
I can't just do:
$user->update($new_user_data);
What's the proper way? I hope not a foreach
.
The following does work, however. Is this the way to go?
User::where("id", "=", $user->id)->update($new_user_data);
The problem with the last one (besides it being clunky) is that when using it from an object context, the updated fields are not visible in the $this
variable.
$update = ItemTable::where('item_type_id', '=', 1); $update->colour = 'black'; $update->save();
$where['page_id'] = [1,2,3]; $update = [['column' => 'value1'],['column' => 'value2']]; DB::table('my_table')->where($where)->update($update);
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
Using eloquent is great because its have many cool features but when it come to the speed, it slightly slower than query builder because of ORM.
The method you're looking for is fill()
:
$user = User::where ("username","rok"); // note that this shortcut is available if the comparison is = $new_user_data = array(...); $user->fill($new_user_data); $user->save();
Actually, you could do $user->fill($new_user_data)->save();
but I find the separate statements a little easier to read and debug.
You are looking for this:
$user = User::where("username","rok") ->update( array( "email" => "[email protected]", "is_superuser" => 1, // .. ) );
Refer : http://laravel.com/docs/4.2/eloquent#insert-update-delete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With