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

mstnorris's avatar

Get a student's classmates

I'll try and keep this simple. I have two models, User and Module. It is a many to many relationship.

Let's take the authenticated user for example, they take six modules. I would like to find the other users who also take those same six modules.

Can this be done with Eloquent? I know it will be a fairly simple SQL query with a join, but an Eloquent solution usually works out best for what I'm working on.

0 likes
1 reply
mstnorris's avatar
mstnorris
OP
Best Answer
Level 55
$classmates = User::whereHas('modules', function ($query) use ($moduleIds) {
    $query->whereIn('id', $moduleIds);
})->get();

Please or to participate in this conversation.