Search the body of 500 blog posts and show the most relevant first.
Results come back in date order instead of relevance. What happened?
Reveal answer
✓ Answer
An orderBy was applied while searching. Put it in when()'s else-callback.
Eloquent performanceLesson 24 of 28
Searching documents? Full text index + MATCH AGAINST, and don't override the score order.
1 min readIntermediateLesson
Search the body of 500 blog posts and show the most relevant first.
Add a full text index and use MATCH ... AGAINST, which also returns a relevance score.
Post::where('body', 'like', '%'.$search.'%')
->latest('published_at')
->get();
// scans every post, no relevance ranking
Post::query()
->when(request('search'), function ($query, $search) {
$query->selectRaw('*, match(title, body) against(? in boolean mode) as score', [$search])
->whereRaw('match(title, body) against(? in boolean mode)', [$search]);
}, function ($query) {
$query->latest('published_at');
})
Uses the full text index and puts the most relevant posts first.
DB::statement('CREATE FULLTEXT INDEX posts_fulltext_index ON posts(title, body) WITH PARSER ngram');
score is the relevance:select id, title, match(title, body) against('fox' in boolean mode) as score
from posts
where match(title, body) against('fox' in boolean mode)
MySQL orders by score automatically when there's no other ordering. Any orderBy overrides it, which is why the default ordering goes in when()'s third argument (the "otherwise" callback).

The boolean-mode full text query in TablePlus returns the three fox posts. Adding the match() expression to the SELECT as score exposes the relevance ranking.
Searching documents? Full text index + MATCH AGAINST, and don't override the score order.
Results come back in date order instead of relevance. What happened?
✓ Answer
An orderBy was applied while searching. Put it in when()'s else-callback.