Don't relay on a model attribute in the relationship. Instead use polymorphic relationship
https://laravel.com/docs/10.x/eloquent-relationships#one-to-one-polymorphic-relations
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am building a table that has either Clients or Leads, so I have two three tables:
I try to get either the client or the lead name by using relationship, in the model:
if ($this->lead_type== 'Lead') { return $this->belongsTo(Lead::class, 'lead') } else { return $this->belongTo(Client::class, 'lead') } If I try to return either one of the twos, I get the result, but when I try to put the if condition, only the second on query returns a value. The first one returns null.
I am using Laravel Query Builder by Spatie.
Don't relay on a model attribute in the relationship. Instead use polymorphic relationship
https://laravel.com/docs/10.x/eloquent-relationships#one-to-one-polymorphic-relations
Please or to participate in this conversation.