Level 32
You can do this by using a polymorphic relationship.
https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want know if somebody has a "bad" opinion about this example.
I really dislike this approach, but i have not found another way to resolve this.
What do you think about this "dynamic" relationship definition ?
Does anyone knows a better way to perform the same ?
class User {
// properties and other methods...
public function profile()
{
if ($this->role === 'teacher') {
return $this->hasOne(TeacherProfile::class);
}
if ($this->role === 'student') {
return $this->hasOne(StudentProfile::class);
}
return $this->hasOne(BaseProfile::class);
}
}
Please or to participate in this conversation.