Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: how to update multiple fields in an Eloquent model?

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.

like image 583
duality_ Avatar asked Feb 14 '13 15:02

duality_


People also ask

How do you update multiple rows from a single query using eloquent fluent?

$update = ItemTable::where('item_type_id', '=', 1); $update->colour = 'black'; $update->save();

How update multiple rows in SQL using single query in Laravel?

$where['page_id'] = [1,2,3]; $update = [['column' => 'value1'],['column' => 'value2']]; DB::table('my_table')->where($where)->update($update);

What is the difference between eloquent and query builder in Laravel?

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.

Is Laravel eloquent slow?

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.


2 Answers

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.

like image 135
J.T. Grimes Avatar answered Oct 14 '22 13:10

J.T. Grimes


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

like image 30
Kumar Ramalingam Avatar answered Oct 14 '22 15:10

Kumar Ramalingam