// 1. Define models (e.g., Post, Video, Comment) // app/Models/Comment.php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; class Comment extends Model { protected $fillable = ['body', 'commentable_id', 'commentable_type']; // Define the polymorphic relationship public function commentable(): MorphTo { return $this->morphTo(); } } // app/Models/Post.php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphMany; class Post extends Model { public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); } } // app/Models/Video.php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphMany; class Video extends Model { public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); } } // 2. Usage examples: $post = App\Models\Post::find(1); $post->comments()->create(['body' => 'Great post!']); $video = App\Models\Video::find(5); $video->comments()->create(['body' => 'Awesome video!']); // Access the commentable parent from a comment $comment = App\Models\Comment::find(1); $parent = $comment->commentable; // Can be a Post or a Video instance echo get_class($parent); // e.g., "App\\Models\\Post"