Skip to content
Advertisement

How do I create a eloquent Polymorphic relation

I have a two eloquent models model User and Retailer. I want to create a new model “Task” where there there should be a field “added_by” which can denote either a user or a retailer.

How can I create the migration for Task so that there is a field that can denote either user or retailer?

JavaScript

How can I create a Task which references a user for example?

JavaScript

Also when I get a eloquent instance of task how can i know if the added_by is referencing to a user or a retailer?

Advertisement

Answer

The syntax for the migration is $table->morphs(...), not $table->morphes(...).

$table->morphs('added_by') will create the columns added_by_id and added_by_type


Option 1: 1-M Polymorphic Relationships

You need to define some relationships in the User, Retailer and Task models

User

JavaScript

Retailer

JavaScript

Task

JavaScript

Eloquent Relationships – One to Many Polymorphic Relations


To add a Task for an User or a Retailer, you use the relationship method.

JavaScript

Eloquent Relationships – Inserting and Updating Related Models


Option 2: M-N Polymorphic Relationships

The other option is to use a Many to Many Polymorphic Relationship between Product and both User and Retailer

You need to define some relationships in the User, Retailer and Product nodels

User

JavaScript

Retailer

JavaScript

Product

JavaScript

Task

JavaScript

Eloquent Relationships – Many to Many Polymorphic Relation


To associate an User or Retailer with a Product (using Task as a morph pivot)

JavaScript

Eloquent Relationships – Updating Many to Many Relationships

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement