#Many to many relationship index query

7 messages · Page 1 of 1 (latest)

hardy comet
#

Hey y'all I have what I hope is a relatively noobish Eloquent question: I have a many to many relationship and I want to filter an index query on an id in the pivot table. Am I missing something simple in the docs for this? In the roles and users example, let's say I want to return a collection of all users that have a specific role_id.

rich tree
#

So for the roles example I think that would be something like Role::query()->with('users')->find(1)->users. This would first indicate to eager load users for the fetched role, then it fetches the role with ID 1 and loads all the users that have this role. You then end up with a collection of users having that role.

#

I am typing this from my phone, so maybe it's not 100% accurate, but what I typed is the idea of how to fetch users with a specific role

#

You could also use having or whereHas without querying the role specifically iirc

hardy comet
#

I'll play around with these ideas and see what I can put together. Thanks for taking a look!

#

Will keep this open for a bit until I find a solution that works and then post it for future reference 🙂

hardy comet
#
Role::query()
    ->when(request('search'), function (EloquentBuilder $query, array $search) {
        $query->whereHas('users', function ($query) {
            $query->whereIn('user_id', request('search'));
        });
    }, function (EloquentBuilder $query) {
        $query->get();
    })
    ->paginate();