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

testy's avatar
Level 1

Scout - How to search in relations and counts?

I have the following Eloquent scope:

return $query->where('title', 'like', '%' . $title . '%')->orWhereHas('alternatives', function($query) use ($title) {
     return $query->where('title', 'like', '%' . $title . '%');
});

^ this scope will be called in controller like this:

return $this->item->findByTitle($title)->with('latestEpisode')->withCount('episodes')->get();

Is there a way to make this happens in Laravel Scout? I have the follwing:

return $this->item->search($title)->get()->load('latestEpisode');

^ few problems here: There isn't a method for withCount for Scout. The second problem is, how do i query the alternatives relation as above in my normal Eloquent scope?

0 likes
4 replies
digital@jfd.co.uk's avatar

Hi All,

Unfortunately it seems that scout results aren't relational at the moment. But you can amend what is being placed in your index via the toSearchableArray() method.

    /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        $array['county'] = $this->county['name'];

        return $array;
    }

In this instance, my user object has a county associated by ID in a lookup table.

I am pulling that data via the eloquent relationship and adding that as a property to the array that is being pushed up to algolia via scout.

https://laravel.com/docs/5.4/scout#configuring-searchable-data

2 likes
thiagodeveloper's avatar

Consegui recuperar os relacionamento da tabela da seguinte forma!

Arquivo: Controller

Event::search($request->get('q'))->get()->load('users');

Please or to participate in this conversation.