How to Update Multiple Records in Laravel?

Last updated on December 29, 2022

There can be different cases where we update records into a database using the Laravel framework. Let’s suppose we have two cases in which we will be updating records in MySQL.

  • Update multiple rows with the same data
  • Update row with different data

Update Multiple Rows with the Same Data

To update multiple rows with the same data, we will need a where clause that helps to update specific rows that need to be updated. Let’s suppose in the users’ table a few users’ countries and cities need to be updated. To do that we will need a user’s ID. Following are the IDs

User IDCountryCity
10GermanyBerlin
11PolandWarsaw
12FranceParis
user table

As you can see, all user’s have different countries and cities which need to be updated with the new ones. So let’s create an update query,

User::whereIn('id',[10,11,12])->update([
    'country' => 'Italy',
    'city'  => 'Rome'
]);

This query updates the country and city for users who have IDs 10, 11, and 12. It has a whereIn() function that accepts two parameters; the first is the column name and the second values are in array format.

Update Row with Different Data

Sometimes we update different data for each user. For example, to update the city for user 10 we will need the following query.

User::where('id',10)->update([
    'city'  => 'Naples'
]);

This query updates the city for user id 10.

Conclusion

To update multiple records with the same data you need to use the whereIn() function along with the update() function in the Laravel framework.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,