Laravel Scout + Meilisearch: How to search only on specific fields

Jian Jye
2 min readJun 22, 2021
Photo by Brian McGowan on Unsplash

I love how easy it is to plug in Laravel Scout and Meilisearch and instantly I get a search engine for my app. Searching by keywords is easy and well-documented. Assuming a Movie model, we could just do this and get a list of results.

Movie::search('Star Wars')->get();

Amazing!

But what if we wanted something more specific. We wanted only the Star Wars movies produced after 1990? We can’t do it as such:

Movie::search('Star Wars AND year >1990')->get();

Does that mean Laravel Scout is a no go?

No way!

Here’s how

Meilisearch has a concept of filtering. To achieve our desired results, we could do this via curl as such:

curl 'http://localhost:7700/indexes/movies_index/search' \
--data '{ "q": "Star Wars", "filters": "year > 1990" }'

Doing it via Laravel Scout is pretty straight-forward as well! All you need is a few extra lines of codes as such:

use MeiliSearch\Endpoints\Indexes;Movie::search('Star Wars', function(Indexes $index, $query, $options) {
$options['filters'] = "year > 1990";
return $index->rawSearch($query, $options);
})->get();

And if we wanted only Episodes 1 to 3, which were produced in 1999, 2002, and 2005 respectively, we could do our filtering as such:

use MeiliSearch\Endpoints\Indexes;Movie::search('Star Wars', function(Indexes $index, $query, $options) {
$options['filters'] = "(year > 1990) AND (year < 2006)";
return $index->rawSearch($query, $options);
})->get();

There you go! You’ve now unleashed the full power of filtering in Meilisearch via Laravel Scout!

--

--

Jian Jye

I write about Laravel, PHP, and web development related articles.