← Back to all snippets
PHP

Implementing Polymorphic One-to-Many Relationships with Eloquent

Discover how to use Laravel Eloquent to create polymorphic one-to-many relationships, allowing a model to belong to more than one other model on a single association.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * Get the parent commentable model (post or video).
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    /**
     * Get all of the post's comments.
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

class Video extends Model
{
    /**
     * Get all of the video's comments.
     */
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// Example usage:
// $post = Post::find(1);
// foreach ($post->comments as $comment) {
//     echo $comment->content;
// }
// $video = Video::find(1);
// foreach ($video->comments as $comment) {
//     echo $comment->content;
// }
// $comment = Comment::find(1);
// $commentable = $comment->commentable; // Can be a Post or a Video instance
How it works: This snippet illustrates polymorphic one-to-many relationships in Laravel Eloquent. A `Comment` model can belong to either a `Post` or a `Video` model via a single `commentable` relationship. The `morphTo` method on the `Comment` model defines the inverse, while `morphMany` on `Post` and `Video` models establishes the forward relationship. This allows for flexible and efficient handling of relationships where a child model can relate to multiple parent models of different types.

Need help integrating this into your project?

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

Hire DigitalCodeLabs