How to update multiple rows in laravel?

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

How to update multiple rows in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , a month 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.