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.

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!

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The legal side of CAD-data protection: how to protect your IP with Legal Tech

Journal 19 — Modular Powerups, Unity Practice

Decoding my 20s — Why you should take up programming?

AutoML Vision Edge: Deploying and Running TensorFlow Models using Docker Containers

Day 25. How to be a better Tech lead?

IT System Administrator

Design Patterns Saga: The Beginning

Passing HTTP headers to another microservice and put them to the log programmatically using Spring…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jian Jye

Jian Jye

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

More from Medium

How to Successfully Upgrade Laravel Applications to the latest version

How to Receive and Respond to Incoming SMS Messages in PHP with Laravel and Plivo

Laravel 8 Create Custom Helper Function Example

How to install Laravel PHP Framework on macOS?