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

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.


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:

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:

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

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

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:

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

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

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