1You may register the morphMap in the boot function of your
2App\Providers\AppServiceProvider class or create a separate service provider
3if you wish.
4
5use Illuminate\Database\Eloquent\Relations\Relation;
6
7Relation::morphMap([
8 'post' => 'App\Models\Post',
9 'video' => 'App\Models\Video',
10]);
1posts
2 id - integer
3 title - string
4 body - text
5
6videos
7 id - integer
8 title - string
9 url - string
10
11comments
12 id - integer
13 body - text
14 commentable_id - integer
15 commentable_type - string
1<?php
2
3namespace App\Models;
4
5use Illuminate\Database\Eloquent\Model;
6
7class Comment extends Model
8{
9 /**
10 * Get the parent commentable model (post or video).
11 */
12 public function commentable()
13 {
14 return $this->morphTo();
15 }
16}
17
18class Post extends Model
19{
20 /**
21 * Get all of the post's comments.
22 */
23 public function comments()
24 {
25 return $this->morphMany(Comment::class, 'commentable');
26 }
27}
28
29class Video extends Model
30{
31 /**
32 * Get all of the video's comments.
33 */
34 public function comments()
35 {
36 return $this->morphMany(Comment::class, 'commentable');
37 }
38}