How to update multiple rows in laravel?

by tressie.damore , in category: PHP Frameworks , 10 months ago

How to update multiple rows in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 6 months ago

@tressie.damore 

To update multiple rows in Laravel, you can use the update method along with the whereIn method. Here's an example of how you can update multiple rows in a table:

1
2
3
4
5
6
7
8
9
$data = [
    ['id' => 1, 'status' => 'active'],
    ['id' => 2, 'status' => 'inactive'],
    ['id' => 3, 'status' => 'active'],
];

DB::table('table_name')
    ->whereIn('id', array_column($data, 'id'))
    ->update(['status' => DB::raw('VALUES(status)')]);


In this example, we have an array called $data which contains the data that we want to update in the table. We use the whereIn method to select the rows we want to update based on the id column. Then, we use the update method to update the status column with the corresponding values in the $data array.


Make sure to replace table_name with the name of the table you want to update and adjust the column names and values based on your specific requirements.

Related Threads:

How to update multiple rows in laravel at once?
How to update multiple rows of a table in laravel?
How to update multiple rows in laravel controller?
How to update specific rows using laravel?
How to insert multiple rows in laravel?
How to save multiple table rows in database using laravel?