Level 28
Use a polymorphic relationship :)
https://laravel.com/docs/6.x/eloquent-relationships#polymorphic-relationships
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have 3 tables
* type a ( class TypeA )
| id | name |
* type b ( class TypeB )
| id | name |
* product ( class Product )
| id | type | type_id | name |
Now I want to set a relationship in Product::type() to relate TypeA/TypeB according to the type field,
public function type()
{
if ($this->type == 'a') {
return $this->belongsTo(TypeA::class, 'type', 'type');
} else if ($this->type == 'b') {
return $this->belongsTo(TypeB::class, 'type', 'type');
}
}
But it doesn't work, What should I do? Thanks.
Please or to participate in this conversation.