Laravel One to Many Polymorphic Relationship Tutorial (ok)

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

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

Factories

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

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

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

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

<?php
namespace Database\Factories;
use App\Models\Video;
use Illuminate\Database\Eloquent\Factories\Factory;
class VideoFactory extends Factory {
  protected $model = Video::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\2014_10_12_000000_create_users_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('users', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string('name');
      $table->string('email')->unique();
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->rememberToken();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('users');
  }
}

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

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

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

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

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCommentsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('comments', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string("body");
      $table->integer('commentable_id');
      $table->string("commentable_type");
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('comments');
  }
}

Seeders

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

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

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

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

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

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

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

Models

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

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
  use HasFactory;
  protected $fillable = [
    'body',
    'commentable_id',
    'commentable_type',
  ];
  /**
   * Get all of the owning commentable models.
   */
  public function commentable() {
    return $this->morphTo();
  }
}

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 post's comments.
  */
  public function comments() {
    return $this->morphMany(Comment::class, 'commentable');
  }
}

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

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Video extends Model {
  use HasFactory;
  protected $fillable = [
    'name',
  ];
  /**
   * Get all of the post's comments.
   */
  public function comments() {
    return $this->morphMany(Comment::class, 'commentable');
  }
}

Controllers

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

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\Video;
class TestController extends Controller {
  public function show() {
    $video = Post::find(1);  
    $comments = $video->comments;
    return view('test')->with(compact('comments'));
  }
}

Routes

C:\xampp\htdocs\test\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */
Route::get('/test', [App\Http\Controllers\TestController::class, 'show'])->name('home');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

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>

Retrieve Records:

Create Records:

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

<?php
namespace App\Http\Controllers;
use App\Models\Post;

class TestController extends Controller {
  public function show() {
    $post          = Post::find(1);
    $comment       = new Comment;
    $comment->body = "Hi ItSolutionStuff.com";
    $post->comments()->save($comment);
    die("gggg");
    // $video    = Post::find(1);
    // $comments = $video->comments;
    // return view('test')->with(compact('comments'));
  }
}

Hoặc

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

Sql

One to Many Polymorphic Model Relationship used when a model belongs to more than one other model on a single association model. For example, If we have posts and videos tables, both need to add comments system. Then you can manage in a single table for both tables. one to many polymorphic relationship in laravel 6, laravel 7, laravel 8 and laravel 9 app.

In this tutorial, you can understand how to create migration with a foreign key schema for polymorphic one to many eloquent relationship, use sync with a pivot table, create records, get all data, delete, update and everything related to one to many relationship.

In this example, i will create "posts", "videos" and "comments" table. each table is connected with each other. now we will create one to many polymorphic relationship with each other by using the 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.

One to Many Polymorphic Relationship will use "morphMany()" and "morphTo()" for relation.

Create Migrations:

Now we have to create migration of "posts", "videos" and "comments" table. we will also add foreign key with posts, videos 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();});

comments table migration:

Schema::create('comments', function (Blueprint $table) {    $table->increments('id');    $table->string("body");    $table->integer('commentable_id');    $table->string("commentable_type");    $table->timestamps();});

Create Models:

Here, we will create Post, Video and Comment table model. we will also use "morphMany()" and "morphTo()" for relationship of both model.

Post Model:

<?php namespace App;use Illuminate\Database\Eloquent\Model; class Post extends Model{    /**     * Get all of the post's comments.     */    public function comments()    {        return $this->morphMany(Comment::class, 'commentable');    }}

Video Model:

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Video extends Model{    /**     * Get all of the post's comments.     */    public function comments()    {        return $this->morphMany(Comment::class, 'commentable');    }}

Comment Model:

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model{    /**     * Get all of the owning commentable models.     */    public function commentable()    {        return $this->morphTo();    }}

Retrieve Records:

$post = Post::find(1);	 dd($post->comments);
$video = Video::find(1);	 dd($video->comments);

Create Records:

$post = Post::find(1);	 $comment = new Comment;$comment->body = "Hi ItSolutionStuff.com"; $post->comments()->save($comment);

Read Also: Laravel One to One Eloquent Relationship Tutorial

$video = Video::find(1);	 $comment = new Comment;$comment->body = "Hi ItSolutionStuff.com"; $video->comments()->save($comment);

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

Last updated