DEV Community

adithyasrinivasan
adithyasrinivasan

Posted on • Originally published at adithya.dev on

Adding Scopes to Laravel Scout Queries

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);
 }
Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)