Nested Comments

A threaded comment system where comments can have unlimited nesting depth via parent_id self-referencing foreign key.

ERD Concept

Self-referencing One-to-Many: Comments belong to a parent comment. Top-level comments have parent_id = null. Replies are nested under their parent.

Tables

comments

id commentable_type commentable_id user_id (FK) parent_id (nullable FK) body is_approved timestamps soft_deletes

Relationships

  • Comment morphTo (commentable)
  • Comment belongsTo User
  • Comment belongsTo Comment (parent)
  • Comment hasMany Comment (replies)

Migration

Migration
Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->morphs('commentable');
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->foreignId('parent_id')->nullable()->constrained('comments')->cascadeOnDelete();
    $table->text('body');
    $table->boolean('is_approved')->default(true);
    $table->timestamps();
    $table->softDeletes();
    $table->index(['commentable_type', 'commentable_id', 'created_at']);
});