The combined query still can't use the first and last name indexes.
Search time
~95 ms3.93 ms
96% lower
Eloquent performanceLesson 10 of 28
Fewer queries isn't the goal. Less total time is.
1 min readIntermediateLesson
The combined query still can't use the first and last name indexes.
Run the company lookup as its own query first, then pass the resulting IDs into the users query.
->orWhereIn('company_id', fn ($q) => $q->select('id')
->from('companies')
->where('name', 'like', $term))
// one query, but the users name indexes still go unused
->orWhereIn('company_id', Company::where('name', 'like', $term)->pluck('id'))
About 25× faster (95 ms to 3.93 ms), even with twice the queries.
Search time
~95 ms3.93 ms
96% lower
Queries
36
more queries, much faster
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.

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.
Fewer queries isn't the goal. Less total time is.
The page now runs twice as many queries. Is that a problem?
✓ Answer
No. Total time dropped from ~95 ms to under 4 ms. Simple queries that use indexes beat one complicated query that doesn't.