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

pasadinhas's avatar

Query pivot table

Hi everyone!

Imagine this scenario: Student can attend many Class and Class can be attended by many Student -- so we have a many-to-many relationship. We have a pivot table class_student with student_id and class_id fields.

How can I make an efficient query (using Eloquent) that given multiple Class finds the set of Student that attends all of them?

Concrete example: Given the table below (in a tuple format), I want to query all the users that attend (at least) Classes 1 and 3. The result should be User 2 and User 3.

(student_id, class_id)

(1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 3)

Note: I read the documentation on pivot tables. I don't think it answers this question.

0 likes
1 reply
lmxdev's avatar
lmxdev
Best Answer
Level 5

isn't it something like:

$students = Student::whereHas('classes', function($q){                           
    $q->whereIn("class.id", [1, 3]);                             
});
1 like

Please or to participate in this conversation.