PHP
Implementing Flexible Data Structures with Eloquent Polymorphic Relationships
Learn to define polymorphic relationships in Laravel Eloquent, allowing a model to belong to multiple other models on a single association type.
// App/Models/Comment.php (Morphto relationship)
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
// App/Models/Post.php (MorphMany relationship)
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// App/Models/Video.php (MorphMany relationship)
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
// Usage:
$post = Post::find(1);
foreach ($post->comments as $comment) {
echo $comment->content;
}
$video = Video::find(1);
$comment = $video->comments()->create(['content' => 'Great video!']);
echo $comment->commentable->title; // Accessing the related video's title
How it works: This snippet illustrates polymorphic relationships, a powerful Eloquent feature where a single model (e.g., `Comment`) can belong to more than one type of model (e.g., `Post` or `Video`). The `morphTo` method on `Comment` defines the relationship, while `morphMany` on `Post` and `Video` links them to comments. This pattern is ideal for building flexible and extensible data structures where a resource can be commented on, tagged, or 'liked' across various model types.