TechnicalEloquent performance

Eloquent performanceLesson 7 of 28

Multi-Column Searching

Wrap each word's OR conditions in their own closure.

2 min readIntermediateLesson

Eloquent performance07

The problem

Search 100,000 users by first name, last name or company name (which lives in another table).

The fix

Split the search into words. Each word must match at least one of the columns.

✕ Instead of this

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

✓ Do this

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));
    });
});

The benefit

Correct results: every word has to match somewhere, so typing more words narrows the list.

Results

Search time

326 ms. the starting point for this chapter

Why it works

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.

Watch out

  • %term% means "contains". It's flexible, but it stops indexes being used. That's the next lesson.

Frame from lesson 7

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.

Key takeaway

Wrap each word's OR conditions in their own closure.

Check yourself

What goes wrong if you drop the inner closure?

Reveal answer

✓ Answer

The ORs aren't grouped, so one word matching any column can satisfy the whole query. You get far too many results.