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.
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 ID | Country | City |
10 | Germany | Berlin |
11 | Poland | Warsaw |
12 | France | Paris |
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.
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.
To update multiple records with the same data you need to use the whereIn() function along with the update() function in the Laravel framework.