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

Hrederik Loffler's avatar

Laravel 8.x polymorphic-relationships

Hi everyone. I'm a new in laravel and i have a question about polymorphic-relationships.

I need to have 3 tables:

-products

-product_types

-attributes

Each product has only one product_types: it's look like iPhone has only phone types...

Next step: each product_types has many attributes, and each product_types have same attributes with different value (price, color, weight...). And some product_types have different attributes (phone has dualsim, laptop has videocard ).

And now i already have 3 table:

Products:

-id
-name
-type_id

Product_types:

-id
-name

Attributes:

-id
-product_id
-type_id
-model(App\Models\Example)
-value(value, that used model has for this product and product_type id)

I can't understand where i need to use morphTo, where morphMany Please help me. Thanks

0 likes
3 replies
fylzero's avatar
fylzero
Best Answer
Level 67

These will be used as relationships on your models.

class Attribute extends Model
{
    /**
     * Get the parent attributable model (post or video).
     */
    public function attributable()
    {
        return $this->morphTo();
    }
}

class Product extends Model
{
    /**
     * Get all of the product's attributes.
     */
    public function attributes()
    {
        return $this->morphMany(Attribute::class, 'attributable');
    }
}

class ProductType extends Model
{
    /**
     * Get all of the product type's attributes.
     */
    public function attributes()
    {
        return $this->morphMany(Attribute::class, 'attributable');
    }
}

Make sure to use the morphs() helper when defining your migration. Under the hood this defines a composite index for you which can help with speed on these tables.

In your attributes table migration:

$table->morphs('attributable');

https://laravel.com/docs/8.x/migrations#column-method-morphs

Sreenu143's avatar

This is such a informative article which helps to programming students .I'm well satisfied after read this informative page. ghdsportsapp

1 like

Please or to participate in this conversation.