Laravel one to many polymorphic relationship tutorial

Hi Guys,

Laravel 8 and 9 Example of one to many polymorphic relationship; In this tutorial, you will learn about the laravel one to many polymorphic relationship and how to create and retrieve records from database tables using this relationship.

One to many polymorphic model relationships are used when one model belongs to more than one other model on an association model. For example, if we have posts and video tables, both need to add a comment system. You can then manage in the same table for both tables.

This is similar to one to many relationships. However, in this regard, a child model may be associated with more than one type of model. For example, in the Media app, the user can comment on both video and audio. Therefore, the comment model may be associated with the video model as well as the audio model.

Laravel one to many polymorphic relationship tutorial

Now, in this example, we will see how to create a relationship between a comment with a video and an audio model. One to many polymorphic relationships use "morphMany ()" and "morphTo ()" for a relationship. So follow the steps below.

Step 1 : Create Migrations

In this relationship, we have three database tables: posts, videos and comments. A profiles table will be related with posts and posts table.

posts table migration 

php artisan make:migration create_posts_table
public function up()
{
   Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body');
        $table->timestamps();
    });
}

videos table migration

php artisan make:migration create_videos_table
public function up()
{
     Schema::create('videos', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');            
         $table->timestamps();
     });
}

comments table migration

php artisan make:migration create_comments_table
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
         $table->increments('id');
         $table->integer('user_id')->unsigned();
         $table->text('body');
         $table->integer('comment_id')->unsigned();
         $table->string('comment_type');
         $table->timestamps();
    });
}

Now, let's look at the migration fields. We have comment_id and comment_type fields in the comments migration.

Migrate that schema to the database.

php artisan migrate

Step 2 : Create Models

Here, we will create a post, video and comment table model. We will also use "morphMany ()" and "morphTo ()" to relate both models.

php artisan make:model Comment
php artisan make:model Post
php artisan make:model Video

Goto App/Models/Comment.php and edit bellow code

Comment Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Goto App/Models/Post.php and edit bellow code

Post Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Goto App/Models/Video.php and edit bellow code

Video Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

You may want to use custom field name for "id" and "type" columns of polymorphic model. You need to ensure that you pass the name of the relationship as the first argument to the morphTo() method. For that, you may use PHP's __FUNCTION__ magic constant. The second and third arguments are name of type and id fields like below:

public function profile()
{
    return $this->morphTo(__FUNCTION__, 'comment_type', 'comment_id');
}

Step 3 : Get and Add Records:

Get Commnets for post

/**
 * Access Post Commnets.
 *
 * @return \Illuminate\Http\Response
 */
public function getCommnets()
{
    $post = Post::find(1);

    dd($post->comments);
}

Get Commnets for Video

/**
 * Access Video Commnets.
 *
 * @return \Illuminate\Http\Response
 */
public function getCommnets()
{
    $video = Video::find(1);

    dd($video->comments);
}

Add Commnets for post:

/**
 * Add Post Commnets.
 *
 * @return \Illuminate\Http\Response
 */
public function addPostCommnets()
{
    $post = Post::find(1);
    $comment = new Comment;
    $comment->body = "Hi this is a one to many polymorphic relationship";
     
    $post->comments()->save($comment);
}

Add Commnets for video:

/**
 * Add Video Commnets.
 *
 * @return \Illuminate\Http\Response
 */
public function addPostCommnets()
{
    $video = Video::find(1);
    $comment = new Comment;
    $comment->body = "Hi this is a one to many polymorphic relationshi";
     
    $video->comments()->save($comment);
}

I hope this will help you to understand one to manye polymorphic relationship in laravel app

All Laravel relationship TUtorials

Laravel one to many polymorphic relationship tutorial