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

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



Mẫu 1.1 xây dựng type  model **App\Models\Post**&#x20;

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2F8tTNHRnECvMm0tDMJmto%2FScreenshot_1.png?alt=media&#x26;token=818aeb84-2a90-4ea4-93e8-d4576f94cc3e" 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%2FdmRkv2YW9gXbpQ0zZflL%2FScreenshot_2.png?alt=media&#x26;token=d86e706e-1087-4be8-bec4-b82e760129f5" 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%2FYhd75kdg2YACXSXWv4OS%2FScreenshot_3.png?alt=media&#x26;token=f1129313-b2af-472a-b413-12e63395b792" 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%2FlTlZLzitqu8w4r1A3zNF%2FScreenshot_4.png?alt=media&#x26;token=df1d0744-522f-4d20-918c-742298825f65" 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%2FpLLqi3KkfwKEl5b8Yn5j%2FScreenshot_5.png?alt=media&#x26;token=d924a9a5-d697-45eb-a01f-33564db2787f" 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%2F5VKlHh9lohs17MAYaSJq%2FScreenshot_6.png?alt=media&#x26;token=8b383c89-0f21-4f7a-8a61-57f63675836a" alt=""><figcaption></figcaption></figure>

```
https://loremflickr.com/320/240
```

```
App/Models/Post
App/Models/User
```

```sql
INSERT INTO `images`(`id`, `imageable_id`, `imageable_type`, `url`) VALUES
(NULL, '1', 'App/Models/Post', 'https://loremflickr.com/320/240'), 
(NULL, '3', 'App/Models/Post', 'https://loremflickr.com/320/240'), 
(NULL, '2', 'App/Models/User', 'https://loremflickr.com/320/240'), 
(NULL, '4', 'App/Models/User', 'https://loremflickr.com/320/240');
```

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

```php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController as 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('/', function () {
    return view('welcome');
});
Route::get('test/{id}', [TestController::class,'index'])->name('index');
Route::get('test2/{id}', [TestController::class,'index2'])->name('index2');
Route::get('test3/{id}', [TestController::class,'index3'])->name('index3');

```

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

```php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Post;
use App\Models\Image;
use Illuminate\Http\Request;
class TestController extends Controller
{
  public function index($id)
  {
    $user = User::find($id);
    $user->image;
  }
  public function index2($id)
  {
    $post = Post::find($id);
    $post->image;
  }
  public function index3($id)
  {
    $post = Post::find($id);
    $image = new Image;
    $image->url = "your_image";
    $post->image()->save($image);
  }
}

```

C:\xampp\htdocs\wayarmy\database\factories\UserFactory.php

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

```

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

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

```

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

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

```

C:\xampp\htdocs\wayarmy\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;
  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  public $timestamps  = false;
  protected $fillable = [
    'name'
  ];
  /**
   * Get the post's image.
   */
  public function image()
  {
    return $this->morphOne(Image::class, 'imageable');
  }
}

```

C:\xampp\htdocs\wayarmy\app\Models\Image.php

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

```

C:\xampp\htdocs\wayarmy\database\migrations\2022\_11\_20\_160032\_create\_images\_table.php

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
          $table->increments('id');
          $table->string("url");
          $table->integer('imageable_id');
          $table->string('imageable_type');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

```

C:\xampp\htdocs\wayarmy\database\migrations\2014\_10\_12\_000000\_create\_users\_table.php

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

```

C:\xampp\htdocs\wayarmy\database\migrations\2022\_11\_17\_164213\_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("name");
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('posts');
  }
}

```

Mẫu 1.2 xây dựng type  model _App\Models\User_

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

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

```

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

```php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Post;
use App\Models\Image;
use Illuminate\Http\Request;
class TestController extends Controller
{
  public function index($id)
  {
    $user = User::find($id);
    $userimage = $user->image;
    echo '<pre>';
    var_export($userimage);
    echo '<pre>';
  }
  public function index2($id)
  {
    $post = Post::find($id);
    $postimage = $post->image;
    echo '<pre>';
    var_export($postimage->url); // your_image
    echo '<pre>';
  }
  public function index3($id)
  {
    $image = new Image;
    $image->url = "your_image";
    $post = Post::find($id);
    $post->image()->save($image);
  }
  public function index4($id)
  {
    $image = new Image;
    $image->url = "your_image_2";
    $user = User::find($id);
    $user->image()->save($image);
  }
}

```

cùng xem kết quả :) 😒



[https://oec.wayarmy.net/test/1](https://oec.wayarmy.net/test/1)

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FolAfEyjzD1aRDlMfpTt3%2FScreenshot_7.png?alt=media&#x26;token=1d9a4e22-7ea5-436b-b3ac-637945816138" alt=""><figcaption></figcaption></figure>

[https://oec.wayarmy.net/test2/3](https://oec.wayarmy.net/test2/3)

<figure><img src="https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FyOFy0udEfB5tZSG6UJ1e%2FScreenshot_8.png?alt=media&#x26;token=4c606bba-14d1-4b91-ac1f-ccf5a6442cfb" alt=""><figcaption></figcaption></figure>

In this laravel 9 polymorphic relationship example, I will discuss about polymorphic relationship in laravel. In this example, I will discuss about laravel polymorphic one to one example. I will discuss about what is polymorphic relationship is and when we need this relationship in the Laravel application.

In this example, we will see polymorphic relationship laravel, laravel polymorphic one to one example, laravel polymorphic migration and laravel save polymorphic relationship. You need to just follow this tutorial to learn the above scenarios.

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

### Polymorphic Relationships in Laravel

In Laravel, a polymorphic relationship allows the child model to belong to more than one type of model using a single association. For example, imagine you are building an application that allows users to share their feedback for posts and videos. In such an application, a `Comment` model might belong to both the `Blog` and `Video` models. Now we know what is polymorphic relationship in laravel. Now we will see when we will use it in our Laravel application.

#### One To One (Polymorphic) Scenario

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

```perl
posts
    id - integer
    name - string
 
users
    id - integer
    name - string
 
images
    id - integer
    url - string
    imageable_id - integer
    imageable_type - string
```

PerlCopy

&#x20;

If we avoid polymorphic relationship schema, then our database schema will look like:

```php
posts:
  id
  title
  content
  
posts_images:
  id
  post_id
  image
  date
  
users:
  id
  name
  
users_images:
  id
  user_id
  image
  date
```

PHPCopy

&#x20;

But look at that our polymorphic schema, how cool it is.  Here, we have three entities: `Post`, `User`, and `Image`. `Post` can have `Image`. `User` can have `Image`. Let's create our migration like:

```php
Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('content');
});

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->text('name');
});

Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->morphs(‘commentable’);
    $table->text('image');
    $table->date('date');
});
```

PHPCopy

&#x20;

> **Read also:** [**Laravel One To One/HasOne Eloquent Relationship Tutorial**](https://www.laravelia.com/post/laravel-one-to-onehasone-eloquent-relationship-tutorial)

&#x20;

> Remember: `$table→morphs('commentable')` would automatically create two columns for the `id` and `type` using the text passed to it, so it will result in `commentable_id` and `commentable_type`.

&#x20;

#### Define One to One Polymorphic Relationship

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

**app/Models/User.php**

```php
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    /**
     * Get the user's image.
     */
    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }
}
```

PHPCopy

&#x20;

Now define the relationship in the Post model like:

**app/Models/Post.php**

```php
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    /**
     * Get the post's image.
     */
    public function image()
    {
        return $this->morphOne(Image::class, 'imageable');
    }
}
```

PHPCopy

&#x20;

Now define the relationship in the Image model like:

**app/Models/Image.php**

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

PHPCopy

&#x20;

To access the image for a User, we can use the `image` property declared in the model.

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

```php
<?php

namespace App\Http\Controllers;

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

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

        $user->image;
    }
}
```

PHPCopy

&#x20;

For retrieving image on a post:

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

        $post->image;
    }
}
```

PHPCopy

&#x20;

#### Save Polymorphic Relationship Data

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

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

        $image = new Image;
        $image->image = "your_image";
 
        $post->image()->save($image);
    }
}
```
