Matthias
Matthias

Reputation: 31

Updating rows in laravel mysql database

I've set up a database and want to update the column status for each row in my UsersController:

I started with this:

User::where('id', '=', 1)->update(['status' => $status]);

This is working, but I need some loop to change all the rows, something like this:

  1. foreach $id from the table
  2. run some code to change individual $status variable
  3. set individual $status value in the 'status' column in each row:

    User::where('id', '=', $id)->update(['status' => $status])
    
  4. end foreach

So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?

Upvotes: 2

Views: 1121

Answers (2)

usrNotFound
usrNotFound

Reputation: 2830

@Serge solution is fine for few records but you should be able to use chuck as @ceejayoz suggested

User::chunk(100, function ($users) {
    $users->each(function ($user) {
        $user->status = getStatus($user);
        $user->save();
    });
});

Upvotes: 3

Serge
Serge

Reputation: 2187

Unless the table contains millions of rows... a simple procedural way of doing it is...

$users = Users::get(); // Gets a collection of all users...
foreach ( $users as $user ) {
    //compute your status
    $user->status = get_your_user_status($user->id);
    $user->save();
}

You could also consider using a more functional approach with map for example...

Upvotes: 2

Related Questions