A large number of Polymorphic relationships are also a little difficult to grasp. For example, if you have posts, videos, and tag tables, you'll need to connect them all to meet your needs, such as having many tags on each post and the same for videos. In addition, several tags are associated with multiple posts or videos. However, we can easily accomplish this with just one table, "taggables." You only need to read the article to understand it.
In the application of Laravel 6, Laravel 7, Laravel 8, and Laravel 9, there is a many to many polymorphic relationship.

In this article, you'll learn to create polymorphic many-to-many relationships using migration with a foreign key schema for one-to-many relationships, sync with a pivot table, create records, attach records, get all records, delete, update, and everything else related to polymorphic many-to-many relationships.

I'll make tables for "posts," "videos," "tags," and "taggables" in this example. Each table is linked to the others. Using the Laravel Eloquent Model, we will now construct many to many polymorphic associations with each other. We'll start with database migration, then move on to modelling, retrieving records, and finally creating records.

For the relation, polymorphic Many to Many Relationship will employ "morphToMany()" and "morphedByMany()"

1. Create Migrations

Now we must migrate the tables "posts," "videos," "tags," and "taggables." So, let's make something like this:

posts table migration
Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $table->timestamps();
});
videos table migration
Schema::create('videos', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $table->timestamps();
});
tags table migration
Schema::create('tags', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $table->timestamps();
});
taggables table migration
Schema::create('taggables', function (Blueprint $table) {
    $table->integer("tag_id");
    $table->integer("taggable_id");
    $table->string("taggable_type");
});


2. Create Models

We'll make a Post, Video, and Tag table model here. For both models' relationships, we'll use "morphToMany()" and "morphedByMany()"

Post Model

<?php 
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Post extends Model
 {
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
 }
?>
Video Model
<?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Video extends Model
 {
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
 }
?>
Tag Model
<?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Tag extends Model
 {
    /**
     * Get all of the posts that are assigned this tag.
     */
    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }
 
    /**
     * Get all of the videos that are assigned this tag.
     */
    public function videos()
    {
        return $this->morphedByMany(Video::class, 'taggable');
    }
 }
?>


3. Retrieve Records

$post = Post::find(1);     
dd($post->tags);

$video = Video::find(1); 
dd($video->tags);

$tag = Tag::find(1);     
dd($tag->posts);

$tag = Tag::find(1);     
dd($tag->videos);


4. Create Records

$post = Post::find(1);     
$tag = new Tag;
$tag->name = "CodeSolutionStuff.com"; 
$post->tags()->save($tag);

$video = Video::find(1);     
$tag = new Tag;
$tag->name = "CodeSolutionStuff.com"; 
$video->tags()->save($tag);

$post = Post::find(1);    
$tag1 = new Tag;
$tag1->name = "CodeSolutionStuff.com";
$tag2 = new Tag;
$tag2->name = "CodeSolutionStuff.com 2";
$post->tags()->saveMany([$tag1, $tag2]);

$video = Video::find(1);    
$tag1 = new Tag;
$tag1->name = "CodeSolutionStuff.com";
$tag2 = new Tag;
$tag2->name = "CodeSolutionStuff.com 2";
$video->tags()->saveMany([$tag1, $tag2]);

$post = Post::find(1);    
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->attach([$tag1->id, $tag2->id]);

$video = Video::find(1);    
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->attach([$tag1->id, $tag2->id]);

$post = Post::find(1);    
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$post->tags()->sync([$tag1->id, $tag2->id]);

$video = Video::find(1);    
$tag1 = Tag::find(3);
$tag2 = Tag::find(4);
$video->tags()->sync([$tag1->id, $tag2->id]);

I hope you will like the content and it will help you to learn Laravel Many to Many Polymorphic Relationship
If you like this content, do share.


Recommended Posts

View All

Laravel CORS Example: How to Enable CORS in Laravel?


In this tutorial, i will teach you how to easily enable CORS (Cross-Origin Resource Sharing) in Laravel and work with it.

Laravel whereHas and orWhereHas Query Example


laravel whereHas and orWhereHas query example, wherehas and orWhereHas query in laravel, how to use wherehas in laravel

Laravel 9 Razorpay Payment Gateway Integration Example


razorpay payment gateway integration in laravel 9, laravel 9 razorpay pay payment example, laravel 9 razorpay integration, razorpay integration in lar...

Laravel 9 ConsoleTvs Charts Tutorial Example


consoletvs/charts laravel 9 ,consoletvs charts laravel 9 ,laravel 9 chart consoletvs ,consoletvs/charts laravel 9 tutorial ,laravel charts,laravel ch...

Laravel Routing Tutorial Step by Step


I'll give you a step-by-step instruction on laravel routing in this blog. We'll demonstrate how to make a new route in Laravel and how to make a route...