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

My second Article on IFB here …

QR Code Scanner in Kotlin

Start Learning python with Exercices

Asyncio Is Not Parallelism. You may have heard that Python asyncio… | by  Peter Xie | Towards Data Science

Helm In Kubernetes: Part 4 — Publish Helm Chart To Artifact Hub using Github Pages

Connecting Drill to python on Mac & Windows

How to Have a Successful Software Development Career

Go vs C# Ease of Use

Python3: Mutable, Immutable… everything is object!

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

Customising Laravel Fortify 2FA methods

Laravel Sanctum with custom expiry time

Migration From an Existing Database(2) | Laravel

Simple roles and permissions package for Laravel