Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Husniddin's avatar

Scout search with query

I need to user search() with custom query.

$model = Products::query()->where('is_active', true)->search('Gucci')->get();

Is that ok to get data from Scout separately and search where using its IDs?

    public function scopeCustomSearch($query, $search): void
    {
        if(is_null($search)) {
            return;
        }

        $scout = $this::search($search)->query(function($query) {
            $query->select('id');
        })->get();

        $query->whereIn('id', $scout->pluck('id'));
    }

I think this is not optimal way but at least it is working )

What do you think guys?

0 likes
1 reply
LaryAI's avatar
Level 58

The approach you've taken in the second code snippet is indeed one way to combine a Scout search with additional query constraints. However, it's not the most efficient because it requires two separate queries: one to Scout and another to the database using the IDs from the Scout results.

Laravel Scout allows you to chain additional query constraints directly on the search query using the query method. This is a more optimal way to apply additional constraints because it only executes a single query. Here's how you can modify your first example to include the is_active constraint:

$model = Products::search('Gucci')
    ->query(function ($query) {
        $query->where('is_active', true);
    })
    ->get();

This code will perform a full-text search for 'Gucci' on the Products model and then apply the is_active constraint to the results. It's more efficient because it leverages Scout's search capabilities while applying additional constraints in the same query.

Remember that the actual implementation may vary depending on the search driver you are using with Laravel Scout (e.g., Algolia, MeiliSearch, etc.), as some drivers may have limitations or specific ways to handle additional constraints. Always refer to the documentation of the search driver you are using for the best practices and capabilities.

Please or to participate in this conversation.