Level 8
I think you can use the 'has many through' relationship to handle this sort of thing. You can read more here: https://laravel.com/docs/9.x/eloquent-relationships#has-many-through
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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()
Please or to participate in this conversation.