PHP
Implementing Polymorphic Relationships in Eloquent
Learn to implement polymorphic relationships in Laravel Eloquent, allowing a model to belong to multiple other models on a single association, enhancing data flexibility.
// 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');
}
}
// app/Models/Comment.php
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// Usage Example:
$post = Post::find(1);
foreach ($post->comments as $comment) {
echo $comment->body;
}
$comment = Comment::find(1);
$commentable = $comment->commentable; // Can be a Post or a Video
How it works: This code illustrates a polymorphic relationship where a 'Comment' can belong to multiple different models (e.g., 'Post' or 'Video'). The `morphMany` method is used on the parent models to define the relationship, while `morphTo` is used on the child model ('Comment'). This pattern abstracts the underlying foreign keys, enabling flexible association of comments with various types of models without needing separate relationship columns for each model type, promoting cleaner database design.