DEV Community

Cover image for Polymorphic Relationship
Code Of Accuracy
Code Of Accuracy

Posted on

Polymorphic Relationship

In Laravel, a polymorphic relationship allows a model to belong to more than one other model on a single association. It is useful when you have multiple models that can have the same type of relationship with another model.

Here's an example of a polymorphic relationship between a Comment model and two other models, Post and Video.

1. First, we need to create the migration for the comments table:

php artisan make:migration create_comments_table --create=comments

Enter fullscreen mode Exit fullscreen mode

2. In the comments migration, we'll add the necessary fields for the comment:

Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->text('body');
    $table->unsignedBigInteger('commentable_id');
    $table->string('commentable_type');
    $table->timestamps();
});

Enter fullscreen mode Exit fullscreen mode

Note that we have added two additional fields to the table commentable_id and commentable_type. These fields are used to store the ID and type of the parent model that the comment belongs to.

3. Next, we'll create the Comment model using the Artisan command:

php artisan make:model Comment

Enter fullscreen mode Exit fullscreen mode

4. Now, let's create the Post and Video models. Both models will have a comments method that defines the polymorphic relationship:

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

Enter fullscreen mode Exit fullscreen mode

In both models, we define the comments method using the morphMany method. This tells Laravel that the Comment model can belong to multiple other models, and that the relationship is polymorphic.

5. Finally, we can create a comment for a post or a video using the comments method:

$post = Post::find(1);

$comment = new Comment;
$comment->body = 'A comment on a post';

$post->comments()->save($comment);

$video = Video::find(1);

$comment = new Comment;
$comment->body = 'A comment on a video';

$video->comments()->save($comment);

Enter fullscreen mode Exit fullscreen mode

In the above code, we first find a Post model and create a new comment for it. We use the save method on the comments relationship to save the comment and associate it with the post. We then do the same for a Video model.

That's it! We've successfully created a polymorphic relationship between a Comment model and two other models, Post and Video.

Top comments (0)