Laravel many to many relationship getting role shared by two user models

Viewed 32

the question is simple if I have a many to many relationship between users and roles and two users have a shared role between them is there an eloquent way to get that shared role or do I have to call each of their roles and use two foreach loops to match their records.

1 Answers

I think the following query should do the trick:

$userId1 = 123; // just some assumption...
$userId2 = 234; // can of course be a user object as well

$roles = Role::query()
    ->whereHas('users', function ($query) use ($userId1) {
        $query->where('users.id', $userId1);
    })
    ->whereHas('users', function ($query) use ($userId2) {
        $query->where('users.id', $userId2);
    })
    ->get();

In words, that query basically means: Give me all roles which are associated to the user with id $userId1 as well as a user with id $userId2.

Related