PHP

Querying Polymorphic Relationships in Laravel Eloquent

Learn how to define and efficiently query polymorphic one-to-many relationships in Laravel Eloquent, allowing models to belong to multiple types of models on a single association.

<?php

// In app/Models/Comment.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

// In app/Models/Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

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

// In app/Models/Video.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

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

// Example Usage (e.g., in a controller or route)

// Get all comments for a post
$post = App\Models\Post::find(1);
$postComments = $post->comments; // Collection of comments

// Get the parent of a comment (can be a Post or a Video)
$comment = App\Models\Comment::find(1);
$commentParent = $comment->commentable; // Can be an instance of Post or Video

// Get comments polymorphic-ly related to posts
$postCommentsThroughPolymorphic = App\Models\Comment::where('commentable_type', App\Models\Post::class)->get();

// Eager load commentable parents
$commentsWithParents = App\Models\Comment::with('commentable')->get();
How it works: Polymorphic relationships allow a model to belong to more than one other model on a single association. For example, a `Comment` model might belong to either a `Post` or a `Video` model. The `morphTo()` method on the child model (`Comment`) defines the relationship, while `morphMany()` on the parent models (`Post`, `Video`) defines the inverse. Laravel automatically handles storing the type (e.g., `App\Models\Post`) and ID of the parent model in the `commentable_type` and `commentable_id` columns of the `comments` table, respectively. This snippet demonstrates how to define these relationships and how to query them, including eager loading the polymorphic parent.

Need help integrating this into your project?

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

Hire DigitalCodeLabs