Use toQuery() on Eloquent collections to convert a set of in-memory models back into an Eloquent query builder for bulk operations.
When you have loaded a collection of models (e.g. through filtering or sorting) and now need to perform a bulk database operation on those exact models (such as mass-updating a column or eager-loading a relationship), querying by IDs manually with Model::whereIn('id', $collection->pluck('id')) is verbose.
The toQuery() method generates an Eloquent builder instance scoped to the collection's primary keys.
Bulk Updates via toQuery()
use App\Models\User;
$inactiveUsers = User::where('last_login_at', '<', now()->subYear())->get();
// Convert collection back into query builder to perform a bulk SQL update
$inactiveUsers->toQuery()->update([
'status' => 'archived',
]);
Eager Loading Relationships on Filtered Collections
// Eager-load relations across the collection via SQL
$inactiveUsers->toQuery()->with('profile')->get();
Summary
- Converts an in-memory
Eloquent\Collectioninto a scopedBuilderinstance. - Automatically handles
WHERE INconstraints matching the collection's primary keys. - Ideal for mass updates and bulk deletions on pre-filtered models.
Related Tips
View all tips →Refresh and Pessimistically Lock Models with refreshForUpdate() in Laravel 13.27
Laravel 13.27 adds refreshForUpdate(), reloading an existing model instance in-place with fresh database attributes while acquiring an exclusive FOR UPDATE row lock.
Scope Pivot Table Queries with Closures in wherePivot() in Laravel 13.26
Laravel 13.26 allows wherePivot() and orWherePivot() to accept closures, enabling direct reuse of local scopes defined on custom Pivot models.