Laravel Many to Many Polymorphic Relationship Tutorial (ok)

https://www.itsolutionstuff.com/post/laravel-many-to-many-polymorphic-relationship-tutorialexample.html

Một ví dụ đã hoàn thành

Create Records:

Factories

C:\xampp\htdocs\test\database\factories\PostFactory.php

<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory {
  protected $model = Post::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name'    => $this->faker->text(10)
    ];
  }
}

Migrations

C:\xampp\htdocs\test\database\migrations\2022_05_10_163113_create_posts_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string("name");
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}

Seeders

C:\xampp\htdocs\test\database\seeders\PostSeeder.php

<?php
namespace Database\Seeders;
use App\Models\Post;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Post::factory()->count(50)->create();
  }
}

Models

C:\xampp\htdocs\test\app\Models\Post.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
  use HasFactory;
  protected $fillable = [
    'name',
  ];
  /**
   * Get all of the tags for the post.
   */
  public function tags() {
    return $this->morphToMany(Tag::class, 'taggable');
  }
}

C:\xampp\htdocs\test\app\Http\Controllers\TestController.php

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\Tag;
class TestController extends Controller {
  public function show() {
    $post = Post::find(1);
    $tag       = new Tag();
    $tag->name = "ItSolutionStuff.com";
    $post->tags()->save($tag);
    // $video    = Post::find(1);
    // $comments = $video->comments;
    // return view('test')->with(compact('comments'));
  }
}

Views

C:\xampp\htdocs\test\resources\views\test.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <link rel="stylesheet" type="text/css" href="{{asset('public/css/app.css')}}">
  </head>
  <body class="antialiased">
    <div class="container">
      <div class="row">
        <h1>Lorem ipsum dolor sit amet 2.</h1>
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
          {{-- @foreach ($comments as $comment)
            <p class="text-danger">{{ $comment->body }}</p>
          @endforeach --}}
        </div>
      </div>
    </div>
  </body>
</html>

Kết quả:

Laravel Many to Many Polymorphic Relationship Tutorial

many to many polymorphic relationship in laravel 6, laravel 7, laravel 8 and laravel 9 application.

In this article, you can understand how to create polymorphic many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many polymorphic relationship.

In this example, i will create "posts", "videos", "tags" and "taggables" tables. each table is connected with each other. now we will create many to many polymorphic relationships with each other by using laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see database table structure on below screen.

Polymorphic Many to Many Relationship will use "morphToMany()" and "morphedByMany()" for relation.

Create Migrations:

Now we have to create migration of "posts", "videos", "tags" and "taggables" table. so let's create like as below:

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

Create Models:

Here, we will create Post, Video and Tag table model. we will also use "morphToMany()" and "morphedByMany()" for relationship of both model.

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

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

Create Records:

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

$post = Post::find(1);	 $tag1 = new Tag;$tag1->name = "ItSolutionStuff.com"; $tag2 = new Tag;$tag2->name = "ItSolutionStuff.com 2"; $post->tags()->saveMany([$tag1, $tag2]);
$video = Video::find(1);	 $tag1 = new Tag;$tag1->name = "ItSolutionStuff.com"; $tag2 = new Tag;$tag2->name = "ItSolutionStuff.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]);

Read Also: Laravel One to One Eloquent Relationship Tutorial

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

I hope you understand of many to many relationship...

*** Click On it and Read in Details of RelationShip types:

Last updated