Why do you need the relationship? Why not just store these roles in the role field? Or did I not understand your questions
Feb 22, 2024
4
Level 1
Dynamic relationship
Assuming there is a User model with a role field (string) and these relation :
// User can be one of these
public function admin(): HasOne
{
return $this->hasOne(Admin::class);
}
public function teacher(): HasOne
{
return $this->hasOne(Teacher::class);
}
public function student(): HasOne
{
return $this->hasOne(Student::class);
}
How can I load the appropriate relation based on the role field? Also, how can I display the data in the view?
- Do I always have to check the role field?
$user
->when($user->role === UserRole::ADMIN, function () use ($user) {
$user->load('admin');
})
->when($user->role === UserRole::TEACHER, function () use ($user) {
$user->load('teacher');
})
->when($user->role === UserRole::STUDENT, function () use ($user) {
$user->load('student');
});
// view
<p>{{ $user->username }}</p>
<p>{{ $user->name }}</p>
...
@if($user->role === UserRole::ADMIN)
{{-- specific admin field --}}
@elseif()
{{-- another specific role field --}}
@endif
- Or should I apply polymorphic relationship?
- Or should I create an additional method?
public function appropriateRole() {
if ($this->role === UserRole::ADMIN) {
return $this->admin();
}
// another check role ...
}
Please or to participate in this conversation.