TechnicalEloquent performance

Eloquent performanceLesson 10 of 28

When it Makes Sense to Run Additional Queries

Fewer queries isn't the goal. Less total time is.

1 min readIntermediateLesson

Eloquent performance10

The problem

The combined query still can't use the first and last name indexes.

The fix

Run the company lookup as its own query first, then pass the resulting IDs into the users query.

✕ Instead of this

->orWhereIn('company_id', fn ($q) => $q->select('id')
    ->from('companies')
    ->where('name', 'like', $term))
// one query, but the users name indexes still go unused

✓ Do this

->orWhereIn('company_id', Company::where('name', 'like', $term)->pluck('id'))

The benefit

About 25× faster (95 ms to 3.93 ms), even with twice the queries.

Results

Search time

~95 ms3.93 ms

96% lower

Queries

36

more queries, much faster

Why it works

Each query is now simple and independent. The company lookup takes under 1 ms with its index, and the users query receives plain IDs, so it can use its name indexes too.

Frame from lesson 10

Running the company lookups as separate queries: Debugbar shows 6 statements, but the total is only 3.93 ms. The quoted "microsoft corp" is kept together as one term.

Key takeaway

Fewer queries isn't the goal. Less total time is.

Check yourself

The page now runs twice as many queries. Is that a problem?

Reveal answer

✓ Answer

No. Total time dropped from ~95 ms to under 4 ms. Simple queries that use indexes beat one complicated query that doesn't.