PHP
Implementing Polymorphic One-to-Many Relationships
Learn how to set up and use polymorphic one-to-many relationships in Laravel Eloquent, allowing a single model to belong to multiple types of models on a single table.
// app/Models/Comment.php
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// app/Models/Post.php
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// app/Models/Video.php
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Usage Example
$post = Post::find(1);
$post->comments()->create(['body' => 'Great post!']);
$video = Video::find(1);
$video->comments()->create(['body' => 'Awesome video!']);
$comment = Comment::find(1);
echo $comment->commentable->title;
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. This snippet shows how a `Comment` model can be related to either a `Post` or a `Video` model using `morphTo()` and `morphMany()`. This is incredibly useful for flexible database designs where common entities (like comments, tags, images) can be associated with various different parent models without needing separate foreign key columns for each.