Benchmark Eloquent and query builder code
Run equivalent Eloquent and query builder snippets several times in LaraBench, then compare timings, SQL, and returned rows.
Direct answer
To benchmark Eloquent against the query builder, make both snippets return the same shape, run each several times against the same connection, and compare the timing distribution rather than a single fastest run. LaraBench Benchmark mode lists every measured run in one table.
When to use this
Use this after you already know what query you want to test. A benchmark will not tell you whether the code is correct; it only gives you a local timing signal for a specific app, dataset, cache state, and database server.
Terminal approach
Laravel's Benchmark helper measures a callback in milliseconds. Run each complete snippet with the same iteration count, result size, and selected columns.
use Illuminate\Support\Benchmark;
Benchmark::measure(
fn () => App\Models\Order::query()
->where('status', 'paid')
->latest()
->limit(50)
->get(['id', 'total', 'created_at']),
iterations: 10,
);LaraBench approach
- Open Benchmarks.
- Create one benchmark for snippet A and one for snippet B.
- Use the same connection, repeat count, and warm-up approach.
- Compare median and outlier runs, not only the best result.
- Open SQL queries when a timing difference needs explanation.
Snippets
Snippet A uses an Eloquent model:
use App\Models\Order;
return Order::query()
->where('status', 'paid')
->latest()
->limit(50)
->get(['id', 'total', 'created_at'])
->map->only(['id', 'total', 'created_at']);Snippet B uses the query builder directly:
use Illuminate\Support\Facades\DB;
return DB::table('orders')
->where('status', 'paid')
->latest()
->limit(50)
->get(['id', 'total', 'created_at'])
->map(fn ($row) => [
'id' => $row->id,
'total' => $row->total,
'created_at' => $row->created_at,
]);Expected result
Both snippets should return the same rows and fields. If the timing differs, inspect the SQL and output shape before changing production code. There is no universal winner between Eloquent and the query builder; the right answer depends on hydration cost, scopes, selected columns, indexes, and how the result is used.
Troubleshooting
- If the result differs, compare global scopes, casts, accessors, and selected columns.
- If the first run is slower, rerun both snippets after the app and database have warmed up.
- If the benchmark is noisy, reduce the work, run more repeats, or move the test closer to the database.
Safety notes
Benchmark read-only code first. A repeated benchmark can multiply writes, dispatches, emails, cache mutations, or external API calls very quickly.
Related workflows
Run the N+1 workflow before benchmarking if the query count is still suspicious.
Run these checks in LaraBench.
The free app includes Run Code, Artisan commands, Docker and SSH connections, saved items, History, logs, and benchmarks.