When I first started to use Meilisearch with Laravel Scout, I wanted to query an Eloquent relationship along with my search. Like everything with Laravel, there was already a solution available. In this tutorial we will expand on the Laravel documentation and provide a few examples of how to include an Eloquent relationship’s model with a Meilsearch indexed record.
Prerequisite
I’m going to assume you already have a properly functioning Meilisearch instance up and running. Along with that, I’m going to assume you are using Laravel Scout with Laravel 9. However, this will work with older versions of Laravel if needed.
This is a really quick article, but is something I implement on most of my Meilisearch instances. The ability to search an index and get important related fields will make the UX of your app so much nicer!
Why would you do this?
Say you have an index of customers. Each of those customers has multiple email addresses. The email addresses are located in a related table in your database, say customer_email_addresses
. When you search for customers with Laravel Scout in your app, allowing the user to search by an email address is crucial. If the email addresses are in a different table, no results would be returned. Luckily, there’s a simple solution to include these relationships in your Meilisearch index.