use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; // --- Database Migrations --- // comments table migration // Schema::create('comments', function (Blueprint $table) { // $table->id(); // $table->string('content'); // $table->morphs('commentable'); // Adds commentable_id (INT) and commentable_type (STRING) // $table->timestamps(); // }); // --- Eloquent Models --- // Comment Model class Comment extends Model { public function commentable() { return $this->morphTo(); } } // Post Model (can have many comments) class Post extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } } // Video Model (can also have many comments) class Video extends Model { public function comments() { return $this->morphMany(Comment::class, 'commentable'); } } // --- Usage Examples --- // Attaching a comment to a Post $post = Post::find(1); $post->comments()->create(['content' => 'Great post!']); // Attaching a comment to a Video $video = Video::find(1); $video->comments()->create(['content' => 'Awesome video!']); // Retrieving comments for a Post $postComments = Post::find(1)->comments; foreach ($postComments as $comment) { echo "Post Comment: " . $comment->content . " "; } // Retrieving comments for a Video $videoComments = Video::find(1)->comments; foreach ($videoComments as $comment) { echo "Video Comment: " . $comment->content . " "; } // Accessing the parent model from a comment $comment = Comment::find(1); echo "Comment by: " . $comment->commentable->title . " (Type: " . $comment->commentable_type . ") ";