The whereHas company check still stops indexes being used. Switching to a join only helps a little (275 to 231 ms).
Search time
~275 ms<100 ms
64% lower
The company name index is now used
Eloquent performanceLesson 9 of 28
Remove dependencies between parts of a query so each part can use its index.
2 min readIntermediateLesson
The whereHas company check still stops indexes being used. Switching to a join only helps a little (275 to 231 ms).
Use whereIn with a subquery. It gets the matching company IDs on its own, separate from the users query.
->orWhereHas('company', fn ($q) => $q->where('name', 'like', $term))
// compares companies against every user row
->orWhereIn('company_id', fn ($q) => $q->select('id')->from('companies')->where('name', 'like', $term))
Under 100 ms (from ~275 ms), because the company name index is now used.
Search time
~275 ms<100 ms
64% lower
The company name index is now used
whereHas and joins compare companies against each user row, so companies become a dependency of the users query. A whereIn subquery doesn't refer to users at all, so the database can run it once and use its index.

The improved scope uses str_getcsv for quoted groups and a trailing-only wildcard (term%). It also uses orWhereIn('company_id', subquery) instead of orWhereHas, which removes the dependency on the users table.
Remove dependencies between parts of a query so each part can use its index.
Why is whereIn('company_id', subquery) faster than whereHas('company') here?
✓ Answer
The subquery doesn't depend on each user row, so it runs independently and can use the company name index.