Laravel Tutorials

Converting Collections to Queries in Laravel Using toQuery()

Published
Converting Collections to Queries in Laravel Using toQuery() image

Working with large datasets in Laravel often requires flexibility in how we manipulate and process data. While collections provide powerful array manipulation methods, sometimes we need to switch back to query builder operations for efficiency. Laravel's toQuery() method bridges this gap by converting collections back into query builders, enabling database-level operations on filtered data sets.

Using toQuery()

The toQuery() method transforms Eloquent collections back into query builder instances, enabling powerful chaining of operations:

// Basic conversion
$users = User::where('status', 'active')->get();
 
$userQuery = $users->toQuery();

Real-World Implementation

Let's build an order processing system with efficient batch operations:

<?php
 
namespace App\Services;
 
use App\Models\Order;
use App\Events\OrdersProcessed;
use Illuminate\Support\Facades\DB;
 
class OrderProcessor
{
public function processReadyOrders()
{
$orders = Order::where('status', 'ready')
->where('scheduled_date', '<=', now())
->get();
 
DB::transaction(function() use ($orders) {
// Convert collection to query for bulk update
$orders->toQuery()->update([
'status' => 'processing',
'processed_at' => now()
]);
// Chain additional operations
$ordersByRegion = $orders->toQuery()
->join('warehouses', 'orders.warehouse_id', '=', 'warehouses.id')
->select('warehouses.region', DB::raw('count(*) as count'))
->groupBy('region')
->get();
 
event(new OrdersProcessed($ordersByRegion));
});
}
 
public function updatePriorities()
{
$urgentOrders = Order::where('priority', 'high')->get();
 
$urgentOrders->toQuery()
->select('orders.*', 'customers.tier')
->join('customers', 'orders.customer_id', '=', 'customers.id')
->where('customers.tier', 'vip')
->update(['priority' => 'critical']);
}
}

This implementation demonstrates:

  • Bulk updates with transaction safety
  • Joining operations after collection conversion
  • Aggregations and grouping

By leveraging toQuery(), you can seamlessly switch between collection and query builder operations, making your Laravel applications more efficient and your database interactions more flexible.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article
PhpStorm 2026.2 Released image

PhpStorm 2026.2 Released

Read article
Laravel Doctor: Diagnose Your App With One Artisan Command image

Laravel Doctor: Diagnose Your App With One Artisan Command

Read article
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article