How to update multiple record using laravel?

Member

by denis , in category: PHP Frameworks , 5 months ago

How to update multiple record using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a month ago

@denis 

To update multiple records in Laravel, you can use the update method on the Eloquent model with a where clause to specify which records to update. Here is an example of how you can update multiple records in a database table using Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Update records that match the specified conditions
$updatedRows = AppUser::where('status', 'active')
               ->update(['status' => 'inactive']);

// Check if any rows were updated
if ($updatedRows > 0) {
    echo 'Records updated successfully!';
} else {
    echo 'No records were updated.';
}


In the above example, we are updating all user records with a status of 'active' to 'inactive'. The update method accepts an array of column-value pairs to update the specified columns for the selected records.


Make sure to replace AppUser with the appropriate Eloquent model class for the database table you want to update.


You can also use other where conditions to further filter the records you want to update. For example, you can use where('id', '>', 10) to update records with an ID greater than 10.