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

colinlongworth's avatar

belongsToMany - Correct way to get a 'hasManyThrough' relationship?

In our initial data model, the User has many Students, and each Student had a number of Enrollments:

User.php

public function students()
{
    return $this->hasMany(Student::class);
}

public function enrollments()
{
    return $this->hasManyThrough(Enrollment::class, Student::class);
}

This worked perfectly but we needed to adjust the data model so multiple Users could interact with the same students.

Note: The reason the User model has an enrollments() function is so that we can use it for rendering / filtering tables of enrollments, as opposed to having to go via the students() relationship, and then get enrollments.

This is the updated User model:

User.php

public function students()
{
    return $this->belongsToMany(Student::class);
}

public function enrollments()
{
    return Enrollment::whereIn('student_id', $this->students()->pluck('student_id'))->with('student');
}

The question however is if the new enrollments() function is correct? And will it work as a replacement to "hasManyThrough" in all regards e.g. Pagination etc? Initially, testing suggests it works as expected but I want to verify.

Or, is there a better way to do do this?

0 likes
0 replies

Please or to participate in this conversation.