In this tutorial, one to many polymorphic laravel examples, I will explain what is polymorphic relationship and when we can use it in our laravel application. One to Many Polymorphic Model Relationships is used when a model belongs to more than one other model on a single association model. For example, If we have posts and videos tables, both need to add a comments system. 

A one-to-many polymorphic relationship in laravel is similar to a one-to-many relation. However, if the child model can belong to more than one type of model using a single association then we can use this one-to-many polymorphic relationship in laravel.

In this laravel one to many polymorphic relationship tutorial, we can understand how to create migration with a foreign key schema for polymorphic one to many eloquent relationship, use sync with a pivot table, create records, get all data, delete, update and everything related to one to many polymorphic relationship.

laravel-9-one-to-many-polymorphic-relationship-example

One To Many (Polymorphic) Scenario

Taking the example mentioned above into consideration, we have two entities: Post and Video. To allow for comments on each of these, we can decide to set up our database like this:

posts
    id - integer
    title - string
    body - text
 
videos
    id - integer
    title - string
    url - string
 
comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

 

Model Structure of Polymorphic Relationship

Now let's define the one-to-many polymorphic relationship in our model class. 

app/Models/Post.php

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

 

Now define the relationship in the Video model like:

app/Models/Video.php

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

 

Now define the relationship in the Comment model like:

app/Models/Comment.php

<?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();
    }
}

 

Read also: Laravel 9 Many To Many | BelongsToMany Eloquent Relationship Tutorial

 

Retrieving The Relationship

Once our database table and models are defined, we may access the relationships via your model's dynamic relationship properties. To access the comments for a Post, we can use the image a property declared in the model.

App\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $post = Post::find($id);
 
        foreach ($post->comments as $comment) {
            //
        }
    }
}

 

For retrieving comments for a video:

App\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use App\Models\Video;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $video = Video::find($id);
 
        foreach ($video->comments as $comment) {
            //
        }
    }
}

 

Save Polymorphic Relationship Data

If we want to save or create polymorphic relationship data then we can follow the below structure:

App\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $post = Post::find($id);

        $comment = new Comment;
        $comment->body = "text";
 
        $post->comment()->save($comments);
    }
}

 

Recommended: Laravel One To One Polymorphic Relationship Example

 

Conclusion

We have tried to discuss the basic concept of one to many polymorphic relationships and their possible use cases in laravel applications. We should also note that one to many polymorphic relationships are not a perfect solution to everything and should only be used when convenient or feels like the right way to go.