Appearance
Eloquent model mass update
To update multiple records in Laravel, you can use the update() method on the query builder or on an Eloquent model instance.
Here is an example of using the query builder to update all records in the "users" table, setting the "active" column to 1:
Example of query builder mass update in Laravel
php
DB::table('users')->update(['active' => 1]);You can also use the update() method on an Eloquent model to update specific records by chaining constraints:
Example of using the update() method on a model instance to update specific records in Laravel
php
$users = User::where('votes', '>', 100)->update(['status' => 2]);
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
You can also use the updateOrCreate method to update an existing record or create a new one if it does not exist. Note that this method handles single records rather than mass updates.
Example of using the updateOrCreate method to update or create a new record in Laravel
php
$user = User::updateOrCreate(
['email' => '[email protected]'],
['name' => 'John']
);It's important to note that when using Eloquent's update() method, the updated_at column will be automatically updated with the current timestamp. However, this method bypasses model events such as saving and saved.