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

ynoth25's avatar

Laravel Relationship

I have tables (course, teacher, student and enrollment).

Inside my enrollment table I have student_id, teacher_id, course_id, I'm having a hard time deciding which is which and how to query like get the courses that the students took together with the teacher details.

0 likes
4 replies
SilenceBringer's avatar
Level 55

@ynoth25 enrollment belongsTo student, teacher and course https://laravel.com/docs/8.x/eloquent-relationships#one-to-many-inverse

Student, teacher and course hasMany enrollments https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

get the courses that the students took together with the teacher details.

Course::whereHas('enrollments', fn ($query) => $query->where(<you condition for enrollments>))
	->with('enrollments.teacher')
	->get()
1 like
ynoth25's avatar

@SilenceBringer Tried your suggestion and it worked, but I have this 10, 000 plus records of enrollment and tried to query enrollment with (student, teacher, lesson) relationship and it took me to have 10000+ models being used as shown in Laravel debug bar. Is it normal?

1 like
ynoth25's avatar

In hasManyThrough, do you think I have to restructure my enrollment table? because a teacher can belong to a lesson and lesson can also belong to teacher. and student hasMany enrollment and enrollment belongs to student.

That was what I understood so far.

Please or to participate in this conversation.