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

colinlongworth's avatar

Get the belongsToMany of a belongsToMany

Firstly, I apologise for the title, as I'm not sure of the best way to word this.

I have a Site model, which has a belongsToMany to a Group

class Site extends Model {

	public function groups()
    {
        return $this->belongsToMany(Group::class);
    }
}

This Group has a belongsToMany relationship to Students:

class Group extends Model {

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

What is the most optimum way to get all the Students are are part of a site? Is there an appropriate 'through' method here? Or is the only way as such:

foreach($site->groups()->cursor() as $group) {
		$students = $group->students()->get();
}

I can't help but feel there is a nice way to do something like:

$site->students()->get()
0 likes
1 reply

Please or to participate in this conversation.