Laravel Polymorphic Comments Relationship

Laravel Polymorphic Comments Relationship

Laravel Polymorphic Comments Relationship

One comments table works for any model — no duplicate tables needed.

// Migration
Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->morphs('commentable'); // adds commentable_id + commentable_type
    $table->text('body');
    $table->timestamps();
});

// app/Models/Comment.php
class Comment extends Model
{
    public function commentable(): MorphTo
    {
        return $this->morphTo();
    }
}

// app/Models/Article.php
class Article extends Model
{
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// Usage
$article->comments()->create(['user_id' => 1, 'body' => 'Great post!']);
$comments = $article->comments()->latest()->get();
All Comments