enriqg9's avatar

How to query by a hasMany relation and paginate?

I have a Company model which has a ManyToMany relationship Trade. I am working on a Company Directory but I would like to be able to filter Companies by Trade, for example, select all the Companies that have a trade of 1 and 4 and then make a pagination object.

Right now I am doing my query like this:


Trade::with('companies')->whereIn('id', Request::get('trades'))->get();

But that returns a Trade collection with the companies, which I am only interested on the companies that match certain trades. How can I do such query and then do a pagination object?

0 likes
1 reply
enriqg9's avatar
enriqg9
OP
Best Answer
Level 13

I was able to achieve this with the following query:

Company::whereHas('trades', function ($query)
        {
            $query->whereIn('id', Request::get('trades'));
        })->paginate(10);
1 like

Please or to participate in this conversation.