This is the sixth & last blog post of Laravel relationship Model tutorial series. In this tutorial, we are going to learn how to implement Many to Many Polymorphic relationship within our Laravel application. Imagine that, If we have posts, videos, and tag tables, and we require to connect with each other with your requirement like every post have multiple tags and same for videos too. Also every tag many are connected with multiple post or multiple videos too. But we can easily do it using just one table "taggables". Just read the article and you got it.
Prerequisites
Laravel
To Continue with this tutorial, you should have installed Laravel in your pc. If you are still not installed Laravel in your machine you can configure it from here.
Setting up the Project
First you need to create a new laravel project by running below command in your terminal
Then navigate to your project directory by using below command in your terminal
1
cd polymorphic-example
In here we will use “morphToMany()” and “morphedByMany()” relations.
Create Migration
Now we have to create migration of "posts", "videos", "tags" and "taggables" tables.
Posts table migration
1 2 3 4 5
Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string("name"); $table->timestamps(); });
Videos table migration
1 2 3 4 5
Schema::create('videos', function (Blueprint $table) { $table->increments('id'); $table->string("name"); $table->timestamps(); });
Tags table migration
1 2 3 4 5
Schema::create('tags', function (Blueprint $table) { $table->increments('id'); $table->string("name"); $table->timestamps(); });
Taggables table migration
1 2 3 4 5
Schema::create('taggables', function (Blueprint $table) { $table->integer("tag_id"); $table->integer("taggable_id"); $table->string("taggable_type"); });
Create Models
Now we need to create Post, Video and Comment model. we will also use "morphToMany()" and "morphedByMany()" for relationship of both model.
Post Model:
1 2 3 4 5 6 7 8 9 10 11 12
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } }
Video Model:
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Video extends Model { public function tags() { return $this->morphToMany(Tag::class, 'taggable'); } }
Tag Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Tag extends Model { public function posts() { return $this->morphedByMany(Post::class, 'taggable'); }
public function videos() { return $this->morphedByMany(Video::class, 'taggable'); } }
In this tutorial, we learn how to implement many to many polymorphic relationship within Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.