Benefits of polymorphism in user roles
instead of having multiple relationships like
$user->student_profile, $user->teacher_profile, $user->parent_profile.
you can just create a polymorphic relationship like
$user->profile and it will return either a model for student, teacher or parent...
But here's a problematic situation
The student model has a method called enroll... yet both teacherandparent` do not...
The Question
How should one handle such a situation?
Here are my thoughts
- should I just add an
if statement?
if (method_exists($user->profile, 'Enroll')){
$user->profile->enroll();
}
- should I use an interface (
Enrollable)? but still, have an if statement
if ( $user->profile instanceof Enrollable ){
$user->profile->enroll();
}
Note: This is my most preferred method
- These are Role-based methods maybe I can use something like
Can?
if ($user->can('enroll')) {
$user->profile->enroll();
}
Note: The problem here is that a parent has the permission to enroll their children which is a student, therefore this is not preferable. unless you'll have two permission types be enrolled and enroll, but still not my preferred method.
- Maybe there is another way? Hmm... 🤔 let me ask the awesome people from Laracast.