Laravel 9 Many to Many Polymorphic Relationship Example

In this example, we will create a many to many polymorphic relationship between a user and a post.

First, we need to create the models for the user and post.

User Model

morphToMany(‘App\Post’, ‘postable’);
}
}

Post Model

morphedByMany(‘App\User’, ‘postable’);
}
}

Next, we need to create the migration for the postables table.

unsignedBigInteger(‘post_id’);
$table->unsignedBigInteger(‘postable_id’);
$table->string(‘postable_type’);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(‘postables’);
}
}

Finally, we need to create the relationship between the user and post models.

morphToMany(‘App\Post’, ‘postable’)->withTimestamps();
}
}

morphedByMany(‘App\User’, ‘postable’)->withTimestamps();
}
}

Now, we can use the relationship to attach a post to a user and vice versa.

// Attach a post to a user
$user->posts()->attach($post);

// Detach a post from a user
$user->posts()->detach($post);

// Get all posts for a user
$user->posts;

// Get all users for a post
$post->users;
[ad_1]

Laravel 9 many to many polymorphic relationship example; In this tutorial, you will learn about laravel many to many polymorphic relationship and how to use create, and retrieve records from database tables using this relationship.

Using “morphToMany()” and “morphedByMany()” eloquent method, you can create Many to Many Polymorphic Relationship in your laravel eloquent models.

This tutorial show

Laravel Many to Many Polymorphic Relationship Example

Follow the following steps to create many to many polymorphic relationship and learn how to use this relationship:

Step 1: Create Migration File

First of all, create posts, videos, tags and taggables migration files with following files:

database/migrations/posts

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

    $table->bigIncrements('id');

    $table->string("name");

    $table->timestamps();

});

database/migrations/videos 

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

    $table->bigIncrements('id');

    $table->string("name");

    $table->timestamps();

});

database/migrations/tags 

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

    $table->bigIncrements('id');

    $table->string("name");

    $table->timestamps();

});

database/migrations/taggables 

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

    $table->integer("tag_id");

    $table->integer("taggable_id");

    $table->string("taggable_type");

});

Step 2: Create many to many polymorphic relationships in model

Next, create many to many polymorphic relationships as follow:

app/Post.php

namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
   
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

app/Video.php

namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Video extends Model
{

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

app/Tag.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');
    }
}

Step 3: Insert and retrieve a record using many to many polymorphic relationship

Now you will learn how to insert and retrieve a record from posts, videos tags, and taggables table using many to many polymorphic relationship:

Retrieve Records From table

Find post tags as follow:

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

Find video tags as follow:

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

and you can find post and video of a specific tag like

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

Insert Records in Table

Insert tag for the following post into DB table as follow:

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

Insert tag for the following video into DB table as follow:

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

Insert Multiple Tags for Post:

$post = Post::find(1);	
 
$tag1 = new Tag;
$tag1->name = "Laravel";
 
$tag2 = new Tag;
$tag2->name = "jQuery";
 
$post->tags()->saveMany([$tag1, $tag2]);

Using sync or attach to insert multiple tag as follow:

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

Or use sync

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

Conclusion

In this tutorial, you have learned how to create and use many to many polymorphic relationship in laravel apps.

Recommended Laravel Tutorials

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00