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

alchermd's avatar

How do I set relationships with conditions?

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!

0 likes
3 replies
rin4ik's avatar
class Exam extends Model
{
    public function student()
    {
        $this->belongsTo(Student::class);
    }

    public function teacher()
    {
        $this->belongsTo(Teacher::class);
    }
}
alchermd's avatar

@rin4ik I don't have a Student or Teacher class; all I have is the default User class that uses a role_id field to determine its roles.

asdrubal's avatar

Just do something along those lines:

   public function audits() {
        return $this->belongsToMany('App\Audits', 'audit_question', 'question_id', 'audit_id');
    }

     public function inaudits() {
        return $this->belongsToMany('App\Audits', 'audit_question', 'question_id', 'audit_id')->where('active', 'Y');
    }

One relation to get all audits, another to get those active. In your case I would go:

    public function student()
    {
        $this->belongsTo('App\User)->where('name','Student');
    }

    public function teacher()
    {
        $this->belongsTo(App\User)->where('name','Teacher');
    }

Please or to participate in this conversation.