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

raflisss's avatar

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?

  1. 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
  1. Or should I apply polymorphic relationship?
  2. Or should I create an additional method?
public function appropriateRole() {
  if ($this->role === UserRole::ADMIN) {
    return $this->admin();
  }
// another check role ...
}
0 likes
4 replies
alazark's avatar

Why do you need the relationship? Why not just store these roles in the role field? Or did I not understand your questions

raflisss's avatar

@alazark I store role name in role field (User Model), when $user->role === UserRole::STUDENT (UserRole is Enum), i need to load student relationship. Student Model has fields like grade, major, and others which Admin and Teacher Model Doesn't have

alazark's avatar

I agree with @gych using a polymorphic relationship I believe you can easily accomplish what you wish.

1 like

Please or to participate in this conversation.