Adding Scopes to Laravel Scout Queries
1 min read

Adding Scopes to Laravel Scout Queries

Including Local scopes to a Laravel Eloquent model

I included a new section for four day work week jobs and when building the logic for that, I wanted to make use of scopes that are present in the eloquent model. I use Laravel Scout to offload some of the work.

Scope scopeIsPublished has an easy boolean check against the database like this:

<?php

//model definition

 public function scopeIsPublished($query)
 {
   return $query->where('is_published', true);
 }

With Scout, I wanted to include this when a user searches for a job. So naturally, this was what I ended up with.

<?php

//logic
$query = Jobs::search('search text')
            ->onlyPublished()
			->otherConditions();
           

I was surprised when the results were unfiltered so I looked a little into the support for scopes in Laravel Scout. On the model instance, ScoutBuilder exposes a handy callback for query so you can use it like this.

<?php

//logic
$query = Jobs::search('search text')
            ->query(function ($query){
                return $query->onlyPublished();
            })
			->otherConditions();
           

This helped get the expected results and should work with all providers Algolia, Elasticsearch, Meilisearch, etc.