Search 100,000 users by first name, last name or company name (which lives in another table).
Search time
326 ms. the starting point for this chapter
Eloquent performanceLesson 7 of 28
Wrap each word's OR conditions in their own closure.
2 min readIntermediateLesson
Search 100,000 users by first name, last name or company name (which lives in another table).
Split the search into words. Each word must match at least one of the columns.
foreach (explode(' ', $terms) as $term) {
$query->where('first_name', 'like', "%$term%")
->orWhere('last_name', 'like', "%$term%")
->orWhereHas('company', fn ($q) => $q->where('name', 'like', "%$term%"));
}
// ORs aren't grouped, so any match anywhere passes
In scopeSearch($query, string $terms = null):
collect(explode(' ', $terms))->filter()->each(function ($term) use ($query) {
$term = '%'.$term.'%';
$query->where(function ($query) use ($term) {
$query->where('first_name', 'like', $term)
->orWhere('last_name', 'like', $term)
->orWhereHas('company', fn ($q) => $q->where('name', 'like', $term));
});
});
Correct results: every word has to match somewhere, so typing more words narrows the list.
Search time
326 ms. the starting point for this chapter
Each word's orWheres are wrapped in a closure, which becomes brackets in SQL: (first like a OR last like a) AND (first like b OR ...). More words means fewer, better matches.
%term% means "contains". It's flexible, but it stops indexes being used. That's the next lesson.
The first version of scopeSearch. Terms are split on spaces, each keyword's where / orWhere / orWhereHas is wrapped in its own closure, and %term% wildcards are used.
Wrap each word's OR conditions in their own closure.
What goes wrong if you drop the inner closure?
✓ Answer
The ORs aren't grouped, so one word matching any column can satisfy the whole query. You get far too many results.