mevlutozdemir's avatar

Laravel Scout get relationship data on search

Hello,

I'm using Laravel Scout in combination with Algolia.

I can search and everything works fine, but I have one question. I have 2 tables: User and Dealer, how can I get the Dealer associated with the User?

Something like this: User::search($query)->with('dealer')->paginate(20).

Hope that anyone can help me.

Greetz,

0 likes
7 replies
Lars-Janssen's avatar

I had the same question yesterday here.

return Message::search($search)->paginate(4)->load('dealer');
mevlutozdemir's avatar

Hey Lars,

Thank you for your reply,

I tried that, but that returns an collection. I need a LengthAwarePaginator.

mevlutozdemir's avatar
mevlutozdemir
OP
Best Answer
Level 4

Found it! Thanks to Taylor Otwell himself for his reply on my tweet.

Solution:

$users = User::search($query)->paginate(25); $users->load('dealer');

$user will be the result now.

This returns an LengthAwarePaginator with the loaded relations.

14 likes
asolopovas's avatar

If I use load it returns Collection instead of LengthAwarePaginator, could please someone advice and why it happens? I can't seem to find the solution for this.

Artistan's avatar

Paginator->load uses a magic method to call the load method on the model collection.

        /** @var LengthAwarePaginator $users */
        $paginatedResults = User::search($query)->paginate(5);
        
        /** @var User[] $modelCollection */
        /*$modelCollection = */ $paginatedResults->load('dealer');
        
        // LengthAwarePaginator->load calls load on the "items" within the paginator
        // it @returns a collection, but also updates the existing items within the Paginator
        // do not use the return value, continue to use the Paginator $paginatedResults

little more details... https://gist.github.com/Artistan/fea3e21f149fdf845e530299bcff37d4

Robstar's avatar

@MEVLUTOZDEMIR - Just to improve the answer from @mevlutozdemir and @somewhat, you could use Laravel's tap() helper, allowing you to have a single return from your method call:

return tap(User::search($phrase)->paginate(25), function ($users) {
    /** @var \Illuminate\Database\Eloquent\Collection $users */
    return $users->load('dealer');
});
3 likes

Please or to participate in this conversation.