---
description: >-
  https://www.laravelia.com/post/laravel-9-one-to-many-polymorphic-relationship-example
---

# Laravel 9 One To Many Polymorphic Relationship Example (ok)

Mẫu 1.1 sử dụng model **App\Models\Post**

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FTEN1HzxR5OJDcB27PWA1%2FScreenshot_1.png?alt=media&#x26;token=5f860cc8-69e1-4523-9879-da1d3d198959" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FlM9aj8HiWdHeWfLyA28u%2FScreenshot_2.png?alt=media&#x26;token=45e5983f-c225-42bb-8ba4-00a398dd6c3e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FYD5aymXYTalGV5mAD4iQ%2FScreenshot_3.png?alt=media&#x26;token=81188e21-60e0-4e10-b6e9-d11fa339fdda" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FVSwJEIX8sHREvo0EmrqY%2FScreenshot_4.png?alt=media&#x26;token=32df3c10-c794-4d52-9993-8fc9005ac5dd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2Fi227vjSETZZZ4vkGlKK1%2FScreenshot_5.png?alt=media&#x26;token=60286871-639e-4649-880e-77e46e3b0f81" alt=""><figcaption></figcaption></figure>

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

```php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;
/*
|--------------------------------------------------------------------------
| 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/{id}', [TestController::class,'index']);
Route::get('/test2/{id}', [TestController::class,'index2']);
Route::get('/test3/{id}', [TestController::class,'index3']);
Route::get('/test4/{id}', [TestController::class,'index4']);
Route::get('/test5/{id}', [TestController::class,'index5']);
```

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

```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Post;
use App\Models\Video;
use App\Models\Comment;
class TestController extends Controller
{
  public function index($id)
  {
    $post = Post::find($id);
    foreach ($post->comments as $comment) {
      echo $comment->body . "<br/>";
    }
  }
  public function index2($id)
  {
    $video = Video::find($id);
    foreach ($video->comments as $comment) {
      echo '<pre>';
      var_export($comment);
      echo '<pre>';
    }
  }
  public function index3($id)
  {
    $video = Video::find($id);
    foreach ($video->comments as $comment) {
      echo '<pre>';
      var_export($comment);
      echo '<pre>';
    }
  }
  public function index4($id)
  {
    $post = Post::find($id);
    $comment = new Comment;
    $comment->body = "Lorem ipsum dolor sit amet, consectetur adip 1";
    $post->comments()->save($comment);
  }
  public function index5($id)
  {
    $video = Video::find($id);
    $comment = new Comment;
    $comment->body = "Lorem ipsum dolor sit amet, consectetur adip 2";
    $video->comments()->save($comment);
  }
  public function savepost($id)
  {
    $post = Post::find($id);
    $comment = new Comment;
    $comment->body = "text";
    $post->comments()->save($comment);
  }
  public function savevideo($id)
  {
    $video = Video::find($id);
    $comment = new Comment;
    $comment->body = "text";
    $video->commcommentsent()->save($comment);
  }
}

```

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FTyQUYHCDs8sZDv1R86do%2Fimage.png?alt=media&#x26;token=6ad54763-b7a1-4365-83e5-def0e5a1c06e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2Fgr5e3bq5cIZWj8qAnXJ0%2Fimage.png?alt=media&#x26;token=b0f27b4e-086f-47a4-9e06-8b67854e07bd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2Fh83PXXyykHLdv9wRVkby%2Fimage.png?alt=media&#x26;token=86e0bcd4-986f-4811-9c9b-ebea8bf6541d" alt=""><figcaption></figcaption></figure>

C:\xampp\htdocs\songkhoe\database\migrations\2022\_11\_21\_020348\_create\_posts\_table.php

```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->increments("id");
      $table->string('title');
      $table->string('body');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('posts');
  }
}
```

C:\xampp\htdocs\songkhoe\database\migrations\2022\_11\_21\_020832\_create\_videos\_table.php

```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->increments("id");
      $table->string('title');
      $table->string('url');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('videos');
  }
}p
```

C:\xampp\htdocs\songkhoe\database\migrations\2022\_11\_21\_020937\_create\_comments\_table.php

```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->increments("id");
      $table->string('body');
      $table->integer('commentable_id');
      $table->string('commentable_type');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('comments');
  }
}
```

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

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

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

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

C:\xampp\htdocs\songkhoe\database\seeders\DatabaseSeeder.php

```php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Post;
use App\Models\Video;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run()
  {
    User::factory(10)->create();
    Post::factory(10)->create();
    Video::factory(10)->create();
  }
}
```

Mẫu 1.2 sử dụng model **App\Models\Video**

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2Frt8wNAVoN674N3wYhAXF%2FScreenshot_6.png?alt=media&#x26;token=f1128f45-5cde-4b25-9025-2a6d1970c76c" alt=""><figcaption></figcaption></figure>

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

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

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

```php
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class VideoFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition()
  {
    return [
      'title' => $this->faker->text(6),
      'url' => $this->faker->url()
    ];
  }
}
```

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

```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
  use HasFactory;
  public $timestamps = false;
  protected $fillable = [
    'body',
    'commentable_id',
    'commentable_type'
  ];
  /**
   * Get the parent commentable model (post or video).
   */
  public function commentable()
  {
    return $this->morphTo();
  }
}
```



In this tutorial, one to many polymorphic laravel examples, I will explain what is polymorphic relationship and when we can use it in our laravel application. One to Many Polymorphic Model Relationships is 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 a comments system.&#x20;

A one-to-many polymorphic relationship in laravel is similar to a one-to-many relation. However, if the child model can belong to more than one type of model using a single association then we can use this one-to-many polymorphic relationship in laravel.

In this laravel one to many polymorphic relationship tutorial, we 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 polymorphic relationship.

![laravel-9-one-to-many-polymorphic-relationship-example](https://www.laravelia.com/public/admin/editor/kcfinder/upload/images/laravel-9-one-to-many-polymorphic-relationship-example.png)

### One To Many (Polymorphic) Scenario

Taking the example mentioned above into consideration, we have two entities: `Post` and `Video`. To allow for `comments` on each of these, we can decide to set up our database like this:

```php
posts
    id - integer
    title - string
    body - text
 
videos
    id - integer
    title - string
    url - string
 
comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string
```

PHPCopy

&#x20;

#### Model Structure of Polymorphic Relationship

Now let's define the one-to-many polymorphic relationship in our model class.&#x20;

**app/Models/Post.php**

```php
<?php
 
namespace App\Models;
 
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');
    }
}
```

PHPCopy

&#x20;

Now define the relationship in the Video model like:

**app/Models/Video.php**

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

PHPCopy

&#x20;

Now define the relationship in the Comment model like:

**app/Models/Comment.php**

```php
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Comment extends Model
{
    /**
     * Get the parent commentable model (post or video).
     */
    public function commentable()
    {
        return $this->morphTo();
    }
}
```

PHPCopy

&#x20;

> **Read also:** [**Laravel 9 Many To Many | BelongsToMany Eloquent Relationship Tutorial**](https://www.laravelia.com/post/laravel-9-many-to-many-belongstomany-eloquent-relationship-tutorial)

&#x20;

**Retrieving The Relationship**

Once our database table and models are defined, we may access the relationships via your model's dynamic relationship properties. To access the comments for a Post, we can use the `image` a property declared in the model.

**App\Http\Controllers\TestController.php**

```php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $post = Post::find($id);
 
        foreach ($post->comments as $comment) {
            //
        }
    }
}
```

PHPCopy

&#x20;

For retrieving comments for a video:

**App\Http\Controllers\TestController.php**

```php
<?php

namespace App\Http\Controllers;

use App\Models\Video;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $video = Video::find($id);
 
        foreach ($video->comments as $comment) {
            //
        }
    }
}
```

PHPCopy

&#x20;

#### Save Polymorphic Relationship Data

If we want to save or create polymorphic relationship data then we can follow the below structure:

**App\Http\Controllers\TestController.php**

```php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $post = Post::find($id);

        $comment = new Comment;
        $comment->body = "text";
 
        $post->comment()->save($comments);
    }
}
```

PHPCopy

&#x20;

> **Recommended:** [**Laravel One To One Polymorphic Relationship Example**](https://www.laravelia.com/post/laravel-one-to-one-polymorphic-relationship-example)

&#x20;

#### Conclusion

We have tried to discuss the basic concept of one to many polymorphic relationships and their possible use cases in laravel applications. We should also note that one to many polymorphic relationships are not a perfect solution to everything and should only be used when convenient or feels like the right way to go.
