Update Many Eloquent Models at Once with toQuery()
Suppose you retrieve a collection of users and want to update the status of every selected user.
A common approach is to loop through the models:
$users = User::where('status', 'pending')->get();
foreach ($users as $user) {
$user->update([
'status' => 'approved',
]);
}
This executes an individual update for each model.
Laravel provides toQuery() to turn an Eloquent collection into a query builder for bulk operations.
Use toQuery()
$users = User::where('status', 'pending')->get();
$users->toQuery()->update([
'status' => 'approved',
]);
Laravel builds a query constrained to the primary keys of the models in the collection, allowing the database to update them together.
Real-World Example
Imagine an admin selects several orders and marks them as processed.
$orders = Order::whereIn('id', $selectedOrderIds)
->where('status', 'pending')
->get();
$orders->toQuery()->update([
'status' => 'processed',
]);
This updates the selected orders with a single bulk update statement.
An Important Difference
Bulk updates do not behave like calling save() on each model individually. Eloquent model events such as saving, saved, updating, and updated are not dispatched for each affected model.
If your application depends on model observers or per-record business logic, account for that before using a bulk update.
When Should You Use It?
- Bulk status changes
- Admin-selected records
- Batch updates after filtering
- Updating a collection of already-retrieved models