← Back to all snippets
PHP

Implement Polymorphic Relationships with Laravel Eloquent

Understand how to create flexible one-to-many or many-to-many polymorphic relationships in Laravel Eloquent, enabling a model to belong to multiple other models.

// app/Models/Comment.php (The 'morphing' model)
class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

// app/Models/Post.php (One of the 'morphable' models)
class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// app/Models/Video.php (Another 'morphable' model)
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; // Accesses title of either the Post or Video model
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. This is particularly useful when you have models like `Comment` or `Image` that might be associated with different types of 'parent' models (e.g., a `Post` or a `Video`). By using `morphTo()` and `morphMany()` (or `morphOne`/`morphToMany`), you avoid duplicating relationship definitions and create a more flexible and scalable database schema and Eloquent model structure.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs