How to update multiple rows in laravel controller?

Member

by daisha , in category: PHP Frameworks , 2 months ago

How to update multiple rows in laravel controller?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 2 months ago

@daisha 

You can update multiple rows in a Laravel controller by first selecting the rows you want to update using a query builder, and then using the update method to update the columns you want to change. Here's an example code snippet to demonstrate how to update multiple rows in a Laravel controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public function updateMultipleRows() {

    // Select the rows you want to update
    $rows = YourModel::where('column_name', 'value')->get();

    // Update the selected rows
    foreach ($rows as $row) {
        $row->update([
            'column_to_update' => 'new_value',
            // add more columns and values to update as needed
        ]);
    }

    return response()->json([
        'message' => 'Multiple rows updated successfully'
    ]);
}


In this example, we are selecting rows from the YourModel model where the column_name is equal to a specific value, and then updating the column_to_update with a new value for each selected row.


Remember to replace YourModel with the actual model you are working with, and modify the where condition and update values according to your specific requirements.