Level 50
class Exam extends Model
{
public function student()
{
$this->belongsTo(Student::class);
}
public function teacher()
{
$this->belongsTo(Teacher::class);
}
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Say I have a User class that can have different role_ids.
>>> $johnTheStudent = User::create([
'name' => 'John Doe',
'major' => 'Information Technology',
'role_id' => Role::where('name', 'Student')->first()->id,
]);
>>> $janeTheTeacher = User::create([
'name' => 'Jane Smith',
'faculty' => 'Social Sciences',
'role_id' => Role::where('name', 'Teacher')->first()->id,
]);
Now, I'd like to create a Exam model that belongs to both a student and a teacher.
>>> $socialScienceExam = Exam::create([
'passing_grade' => 80,
'due_date' => Carbon::tomorrow(),
'student_id' => $johnTheStudent->id,
'teacher_id' => $janeTheTeacher->id,
]);
How do I define these relationships in the Exam model so I can use it like this:
>>> $socialScienceExam->teacher->name
'Jane Doe'
>>> $socialScienceExam->student->major
'Information Technology'
# etc etc
They are both User instances so I'm kinda stuck.
class Exam extends Model
{
public function student()
{
$this->belongsTo(/** A User that has a role_id of a student */);
}
public function teacher()
{
$this->belongsTo(/** A User that has a role_id of a teacher */);
}
}
Thanks in advance for the help, guys!
Please or to participate in this conversation.