How to implement Laravel Scout with Tenancy

Bertrand Son Kintanar
2 min readApr 20, 2018

--

Laravel Scout + Tenancy

I’ve been using the hyn/multi-tenant aka Tenancy Laravel package for quite some time now.

For those who aren’t aware what Tenancy is, it “allows you to easily scaffold a multi-tenant SaaS platform on top of the Laravel framework.”

While the package has been great and all, one of the problems or challenges I face all the time is how to make a certain Laravel package work nicely with tenancy. I even created a tutorial on how to implement Spatie Permissions with Tenancy.

Anyway, enough with the pleasantries and let’s get into code.

This post assumes that you already have multi-tenant working on your project. If not, please head over to the official documentation if you need help with that.

Install Laravel Scout by following the installation instructions on the Laravel website. You can use whatever search drivers you like, but this post is tested using Algolia.

When you’re done setting multi-tenant and scout, our next step is how to make Laravel Scout be aware of which tenant it is trying the search for. One thing you don’t want to happen is for your customers be getting search results from a different tenant. :)

To do this we need to the following:

  • Create a MutatesScoutCommand.php file.
App\Traits\MutatesScoutCommand.php
  • Extend the Laravel\Scout\Console\ImportCommand and use the MutatesScoutCommand file.
App\Console\Scout\ImportCommand.php
  • Add your newly created ImportCommand to App\Console\Kernel file.
App\Console\Kernel.php
  • Create a UsesSearchableTenantConnection trait.

Now that we have all the necessary traits and commands setup, let’s try adding it to one of the Eloquent models.

According to the Tenancy documentation to make an Eloquent model tenant aware you need to add the UsesTenantConnection trait. So similarly with our situation, we’ll add our own UsesSearchableTenantConnection trait instead.

This allows the User model to both use the tenant connection and uses the searchable trait as well. What we need to point out is the use of our own searchableAs() method which is setup in such a way that it adds the database name of the tenant it currently is accessing and use it as the search index.

Now to running the artisan scout import command you can type in:

php artisan tenancy:scout:import "App\Eloquent\User"

instead of the usual

php artisan scout:import "App\Eloquent\User"

You should then get an output similar to:

Imported [App\Eloquent\User] models up to ID: 525777c6–0b42–4242–8ef3–828983ac2254
All [App\Eloquent\User] records have been imported.

This sums it all up. If you have any questions, feel free to leave a comment.

--

--