0
0
LaravelHow-ToBeginner · 4 min read

How to Use morphMany in Eloquent Relationships

Use morphMany in an Eloquent model to define a polymorphic one-to-many relationship where a model can have many related models of different types. It requires defining the morphMany method in the parent model and matching polymorphic columns in the related model's table.
📐

Syntax

The morphMany method defines a polymorphic one-to-many relationship. It takes two main arguments: the related model class and the name of the polymorphic relation.

  • Related Model: The class name of the model that belongs to the parent.
  • Relation Name: The base name for the polymorphic columns (relation_name_id and relation_name_type).
php
public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}
💻

Example

This example shows a Post model that can have many Comment models using morphMany. The comments table has commentable_id and commentable_type columns to store the related model's ID and class.

php
<?php

use Illuminate\Database\Eloquent\Model;

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

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

// Usage example
$post = Post::find(1);
$comments = $post->comments; // Gets all comments related to this post

// Adding a comment
$post->comments()->create(['content' => 'Nice post!']);
Output
Collection of Comment models related to Post with ID 1
⚠️

Common Pitfalls

  • Not adding the polymorphic columns (commentable_id and commentable_type) in the related model's table causes errors.
  • Using inconsistent relation names between morphMany and the database columns leads to mismatches.
  • Forgetting to define the inverse morphTo relationship in the related model breaks the connection.
php
/* Wrong: Missing polymorphic columns in comments table */
// This will cause errors when trying to fetch related comments

/* Right: Ensure migration includes polymorphic columns */
Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->text('content');
    $table->unsignedBigInteger('commentable_id');
    $table->string('commentable_type');
    $table->timestamps();
});
📊

Quick Reference

  • morphMany: Defines polymorphic one-to-many from parent to many children.
  • morphTo: Defines inverse polymorphic relation from child to parent.
  • Database table for related model needs relation_name_id and relation_name_type columns.
  • Relation name must be consistent in code and database.

Key Takeaways

Use morphMany to define polymorphic one-to-many relationships in Eloquent models.
Ensure the related table has the correct polymorphic columns named after the relation.
Always define the inverse morphTo relationship in the related model.
Keep relation names consistent between code and database columns to avoid errors.