How to update multiple rows in laravel at once?

by hal.littel , in category: PHP Frameworks , 3 months ago

How to update multiple rows in laravel at once?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 3 months ago

@hal.littel 

To update multiple rows in Laravel at once, you can use the update method with a where clause to specify which rows to update. Here's an example of how to update multiple rows in a database table in Laravel:

1
2
3
4
5
6
7
8
9
// Update multiple rows with a where clause
$data = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Alice']
];

// Update multiple rows in the users table where the id is 1, 2, or 3
DB::table('users')->whereIn('id', [1, 2, 3])->update($data);


In this example, the update method is called on the users table and the whereIn method is used to specify the rows to update based on the id column. The $data array contains the new values for the name column for the specified rows.


You can also use the Eloquent ORM to update multiple rows at once. Here's an example using Eloquent:

1
2
// Update multiple rows using Eloquent
User::whereIn('id', [1, 2, 3])->update($data);


In this example, the User model is used to update multiple rows in the users table where the id is 1, 2, or 3.


Both methods will update the specified rows in the database table with the new data provided in the $data array.