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

melloman's avatar

Get all that have the same 'belongsTo' relationship

If I have a 'student' model and each student belongs to a 'teacher':

class Student extends Model
{
public function teacher()
    {
        return $this->belongsTo('App\Teacher');
    }
}

Student::find(1)->teacher would give me the teacher of that student but how can I setup a method to find all students that have that same teacher?

0 likes
7 replies
d3xt3r's avatar

Look for hasMany relation. You can set it up, so that you could do Teacher::find(1)->students;

cbuchert's avatar

@melloman , what I do in situations like this is define the inverse of the relationship as well (eg. students have teachers, but teachers also have students).

So, for the student model, you'd have a method something like this one:

public function teachers()
{
    return $this->belongsToMany('App\Teacher', 'student_teacher');
}

And for the teacher model, you'd have a method something like this one:

public function students()
{
    return $this->belongsToMany('App\Student', 'student_teacher');
}

This many to many relationship requires that you have an additional table (here I explicitly name it 'student_teacher'). The table would have at least two columns: student_id (unsigned integer), and teacher_id (also unsigned integer). Once you have this, you can make lookup calls back and forth like you are describing. Eg:

$student = App\Student::first();
$studentsTeachers = $student->teachers()->get();

$teacher = App\Teacher::first();
$teachersStudents = $teacher->students()->get();

This is also nice as it allows you to attach and detach multiple relations with a single call, the sync() method (only available on models that have the 'belongsToMany' relationship, as far as I understand; refer to documentations if that becomes a question).

Hope that helps somewhat.

melloman's avatar

@cbuchert thanks for the help!

Just to confirm, is this the only way to do it?

I currently have a 'teacher_id' column in my 'student' table, is there anyway to create a method that simply finds all the students that have the same 'teacher_id' based on the currently selected record?

E.g. would something along these lines work?

class Student extends Model
{
public function sameTeacher()
    {
        return App\Student::find()->where('teacher_id', $this->teacher_id);
    }
}
d3xt3r's avatar

@jekinney He he he Thanks, :)

@melloman Depending on the relationship you have set up, you can use (one teacher => many students , one student => one teacher) hasMany or belongsToMany (one teacher => many students , one student => many teachers)

In line with your solution, below would also work, but you will not be able to utilise the relationship.

public function sameTeacher()
{
    return static::where('teacher_id', $this->teacher_id)->get();
}

Please or to participate in this conversation.