TechnicalEloquent performance

Eloquent performanceLesson 9 of 28

Faster Options Than whereHas

Remove dependencies between parts of a query so each part can use its index.

2 min readIntermediateLesson

Eloquent performance09

The problem

The whereHas company check still stops indexes being used. Switching to a join only helps a little (275 to 231 ms).

The fix

Use whereIn with a subquery. It gets the matching company IDs on its own, separate from the users query.

✕ Instead of this

->orWhereHas('company', fn ($q) => $q->where('name', 'like', $term))
// compares companies against every user row

✓ Do this

->orWhereIn('company_id', fn ($q) => $q->select('id')->from('companies')->where('name', 'like', $term))

The benefit

Under 100 ms (from ~275 ms), because the company name index is now used.

Results

Search time

~275 ms<100 ms

64% lower

The company name index is now used

Why it works

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.

Watch out

  • The users' first and last name indexes still aren't used. That's the next lesson.

Frame from lesson 9

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.

Key takeaway

Remove dependencies between parts of a query so each part can use its index.

Check yourself

Why is whereIn('company_id', subquery) faster than whereHas('company') here?

Reveal answer

✓ Answer

The subquery doesn't depend on each user row, so it runs independently and can use the company name index.