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

rtacadena's avatar

How to set relationships in Laravel with users having different roles.

For example I am making an app that enables a teacher to manage subjects(add, delete, etc.) while the user will not do the same, he/she will only take the exams made by the teacher.

My question is how can I set the relationship for the teacher and the student since they both use the same Model (User) and table?

Since the teacher must control the subjects, in the User model I will do:

public function subjects() { return $this->hasMany(Subject::class); }

and in the Subject model:

public function user() { return $this->belongsTo(User::class); }

but what about the student?

Since the user has no control of the subjects, he must not have this relationship right? When I do User::subjects(), no matter what the role of the user the subjects() function in the User model will be called right so how can I only assign the role to the teacher not to the student?

Should I do :

public function subjects() { // for student if($this->role == 'student') { return 'You do not own the subjects' }

// for teacher
return $this->hasMany(Subject::class);

}

I will appreciate any help. Thanks!

0 likes
1 reply
midascodebreaker's avatar
Level 17

You dont need to set up a relationship if you are using roles and permission... its a different topic what you are explaining , what you are saying is multi auth... multiple model for student and teacher....

its possible to that relationship student has many teachers and teach belongs to a student

then you need to set up a exam model teacher can create many exams and student can have many exams exams can have many teacher and student a many to many relationship triple pivot

out of the box laravel dont support that type of pivot

there is a package triple pivot

exam_teacher_student

there is a package implements eloquent for triple pivot...

of course if you do intend to use roles and permission and avoid triple pivot to avoid headaches...

you need silber bouncer package i use it... it has a polymorphic model that you can use for many model ....

from there you can do teacher has many exams student has many exams

and leave exams table alone....

and leave the roles permission give authorization for action in your controller

to view the exams create exams and edit....

1 like

Please or to participate in this conversation.