Polymorphic Relationships
One model, many parent types
Polymorphic relationships let a model belong to more than one type of parent using a single association.
A single model (Comment) can belong to multiple parent types. Posts and Videos both have comments through the same table.
Model
Post
Model
Video
Model
Comment
morphMany
Polymorphic columns
commentable_typestring
commentable_idbigint
PHP
// Comment model
public function commentable() {
return $this->morphTo();
}
// Post model
public function comments() {
return $this->morphMany(Comment::class, 'commentable');
}
// Video model
public function comments() {
return $this->morphMany(Comment::class, 'commentable');
}