PHP
Define and Query Polymorphic Relationships
Learn to use Laravel Eloquent's polymorphic relationships, allowing a single model to belong to multiple other models on a dynamic basis, e.g., comments on posts or videos.
// In your models:
// 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');
// }
// }
// Example Usage:
$post = \App\Models\Post::find(1);
$postComment = $post->comments()->create(['body' => 'Great post!']);
$video = \App\Models\Video::find(1);
$videoComment = $video->comments()->create(['body' => 'Awesome video!']);
// Retrieve the "commentable" parent of a comment
$comment = \App\Models\Comment::find(1); // Assuming this comment belongs to a Post
$parent = $comment->commentable; // $parent will be a Post instance
echo "Comment on: " . $parent->title; // Or $parent->name if it was a Video
How it works: Polymorphic relations enable a model (e.g., `Comment`) to belong to more than one other model (e.g., `Post` or `Video`) using a single association. This snippet shows how to define `morphTo` on the child model and `morphMany` on the parent models. It then demonstrates creating comments for different parent types and retrieving the generic `commentable` parent of a specific comment, making your database schema more flexible and reusable for various content types.