PHP

Implementing Polymorphic Relationships with Laravel Eloquent

Understand polymorphic relationships in Laravel Eloquent, allowing a single model to belong to multiple types of other models on a single association, perfect for comments or images.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;

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

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

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

/*
Schema (simplified):

comments table:
- id
- body
- commentable_id (integer)
- commentable_type (string, e.g., 'App\\Models\\Post', 'App\\Models\\Video')
- created_at, updated_at

posts table:
- id
- title

videos table:
- id
- title
*/

// Usage:
// $post = Post::find(1);
// foreach ($post->comments as $comment) {
//     echo $comment->body;
// }

// $comment = Comment::find(1);
// $commentable = $comment->commentable; // Can be a Post or Video model
// echo $commentable->title;
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. In this example, a Comment model can belong to either a Post or a Video model. The Comment model uses morphTo() to define the generic relationship, while Post and Video models use morphMany() to specify that they can have many comments. This is ideal for features like comments, tags, or image uploads where the related item can vary, reducing database redundancy.

Need help integrating this into your project?

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

Hire DigitalCodeLabs