How to use One to Many Polymorphic Relationship in Laravel?

What is Polymorphic Relationship? I will explain by an example and its awesome. Imagine we have stores and products table in our database and we want our users to leave comments on products and store. Using Laravel and Polymorphic Relationships we can implement that in minutes. We will make one comments table and start to save comments from stores and products straight away. So let’s start.

This is code in Products migration.

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->float('price');
            $table->text('description');
            $table->timestamps();
});

And Store migration must look like this

Schema::create('stores', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('address');
            $table->timestamps();
});

and here it is comments migration table finally.

Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->text('body');
            $table->morphs('commentable');
            $table->timestamps();
 });

Now we will add comments() method in our Product table.

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

and same method in Store model.

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

and Comment Model will look like this.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Now everything is done. Now sit back and enjoy. We can add comments very easily.

$comment       = new Comment();
$comment->body = "This Product is awesome";

$product = Product::first();
$product->comments()->save( $comment );

Just like that. We can add comments on for stores in same way.

$comment       = new Comment();
$comment->body = "This Store is awesome";

$store = Store::first();
$store->comments()->save( $comment );

and now we can get comments on products and stores with more ease.

$product->comments;
$store->comments;

Now I hope you understand everything about polymorphic relationship. If you have any question or you are stuck in some situation please leave a comment.