• Post
  • Category
  • Tags
  • About Us
  • Contact Us
Quick Links

Laravel 10 Many To Many Polymorphic Relationship

Aug-04-2023 | Laravel PHP

As a web developer, I have come to realize the immense importance of establishing flexible and scalable database relationships when crafting dynamic and interactive applications. Throughout my journey with Laravel, my go-to PHP framework, I have continually been impressed by its robust features and elegant solutions for managing complex data connections.

Among these features, the "Many To Many Polymorphic" relationship has emerged as a powerful tool, empowering me to establish dynamic associations between multiple models and facilitating seamless data sharing across diverse entities.

In this article, I am excited to embark on an exploration of the Laravel 10 Many To Many Polymorphic relationship and its transformative potential in connecting the "Posts," "Tags," and "Videos" tables in our database.

By harnessing the capabilities of this relationship, I can effortlessly manage tags for both posts and videos, creating a unified system that enhances the organization and searchability of content on my platform.

Throughout our journey, we will delve into the intricacies of setting up the "Posts," "Tags," and "Videos" tables, defining eloquent models, and configuring the Many To Many Polymorphic relationship.

To make things more tangible, I will provide real-world examples that demonstrate how this relationship can be practically applied in diverse scenarios, showcasing its remarkable versatility.

Many to Many Polymorphic relationships are more complicated compared to morph one and morph many relationships. To access many to many polymorphic relationships use morphToMany() and morphedByMany().

So, let us embark on this enriching journey together, as we uncover the power of the Laravel 10 Many To Many Polymorphic relationship.

laravel_10_many_to_many_polymorphic_relationship_example

 

Create Migration

Posts Table

Create a migration file for the "posts" table using the following command.

php artisan make:migration create_posts_table

Open the generated migration file located in the "database/migrations" directory and define the schema for the "posts" table. 

Schema::create('posts', function (Blueprint $table) {

    $table->increments('id');

    $table->string("name");

    $table->timestamps();

});

Tags Table

Create a migration file for the "tags" table using the following command.

php artisan make:migration create_tags_table

Open the generated migration file and define the schema for the "tags" table. 

Schema::create('tags', function (Blueprint $table) {

    $table->increments('id');

    $table->string("name");

    $table->timestamps();

});

Videos Table

Create a migration file for the "videos" table using the following command.

php artisan make:migration create_videos_table

Open the generated migration file and define the schema for the "videos" table. 

Schema::create('videos', function (Blueprint $table) {

    $table->increments('id');

    $table->string("name");

    $table->timestamps();

});

Taggables Table

Create a migration file for the "taggables" table using the following command.

php artisan make:migration create_taggables_table

Open the generated migration file and define the schema for the "taggables" table, which will be used as an intermediary table to establish the many-to-many polymorphic relationship 

Schema::create('taggables', function (Blueprint $table) {

    $table->integer("tag_id");

    $table->integer("taggable_id");

    $table->string("taggable_type");

});

 

Read Also: Laravel 10 One To Many Polymorphic Relationship

 

Create Model

Now, we will create Post, Tag, and Video model. we will also use morphToMany() and morphedByMany() for the relationship of both models.

Post Model

Create a new model file for the "Post" model using the following command.

php artisan make:model Post

Open the generated "Post" model file located in the "app/Models" directory and define the model 

<?php

namespace App\Models;

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

Create a new model file for the "Video" model using the following command.

php artisan make:model Video

Open the generated "Video" model file and define the model. 

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

Tag Model

Create a new model file for the "Tag" model using the following command.

php artisan make:model Tag

Open the generated "Tag" model file and define the model. 

<?php

namespace App\Models;

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');
    }
}

 

Retrieve Records

Once your database table and models are defined, you may access the relationships via your models. For example, to access all of the tags for a post, you may use the tags dynamic relationship property.

$post = Post::find(1);

foreach ($post->tags as $tag) {
    //
}

You may retrieve the parent of a polymorphic relation from the polymorphic child model by accessing the name of the method.

$tag = Tag::find(1);

foreach ($tag->posts as $post) {
    //
}

foreach ($tag->videos as $video) {
    //
}

 

Read Also: Laravel 10 Has Many Through Relationship Example

 

Create Records

Now, we will create a record in the post table. 

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

In this example, we will attach a tag to the post.

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

In this example, we will sync a tag with the post.

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

 


You might also like:

  • Read Also: Laravel 10 many to many Relationship Example
  • Read Also: Laravel 10 one to many Relationship Example
  • Read Also: Laravel 10 one to one Relationship Example
  • Read Also: Laravel 10 Send Mail Using Queue


Laravel
PHP
Laravel 10

RECOMMENDED ARTICLES

Reading articles is highly recommended for skill improvement and knowledge acquisition.

  • Laravel 10 Toastr Notification Example
  • Top 20 Tips and Tricks For Python Programming
  • How to Sort List by Date in Python
  • What is the difference between Array and Object
  • How to Validate Array Input in Laravel 10
  • How to Delete Rows in Excel using Openpyxl in Python
  • How To Create Dynamic Line Chart In Laravel 10
  • Difference between Single Quotes and Double Quotes in PHP
  • How to Sort Array from Smallest to Largest
  • Top 10 Tricks and Tips of Laravel

CATEGORIES

Web development languages can be categorized into different categories.

Laravel
PHP
jQuery
MySQL
CSS
HTML
Bootstrap
Vue JS
Node.js
Other
Python
React JS
Angular
React Native

TAGS

These tags can be used to categorize and organize content related to web development.

Charts
Email
Google API
SEO
Command
Checkbox
Bootstrap
jQuery
Dompdf
Function

RECENT ARTICLES

The recent article focuses on the latest developments to gain new knowledge.

  • 10 Digit Mobile Number Validation i...
  • How to Create Autocomplete Search i...
  • How to Create Autocomplete Search i...
  • How to Add Soft Delete in Laravel 1...
  • How to Delete Relationship Records...
  • How to Send SMS using Twilio in Lar...
  • How to Create Multiple Authenticati...
  • Laravel 10 React Auth Scaffolding E...
  • PHP vs Python: Which is Best for We...
  • How to use Unique Validation on Upd...
Vidvatek
Post
Category
Tags
About Us
Contact Us
Quick Links

Copyright © Vidvatek 2023
Privacy Policy · Terms & Conditions · Disclaimer