Blog Posts & Comments
A classic blog system with posts belonging to users and comments on posts. Comments support nested replies via parent_id.
ERD Concept
One-to-Many with self-referencing: Posts belong to users. Comments belong to posts and users. Comments can have parent comments (nested replies).
Tables
posts
id
user_id (FK)
title
slug
body
status
published_at
views_count
timestamps
soft_deletes
comments
id
post_id (FK)
user_id (FK)
parent_id (nullable FK)
body
timestamps
Relationships
- Post belongsTo User
- Post hasMany Comment
- Comment belongsTo Post
- Comment belongsTo User
- Comment belongsTo Comment (parent)
- Comment hasMany Comment (replies)
Migration
Migration
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->string('slug')->unique();
$table->text('body');
$table->enum('status', ['draft', 'published', 'archived'])->default('draft');
$table->timestamp('published_at')->nullable();
$table->unsignedInteger('views_count')->default(0);
$table->timestamps();
$table->softDeletes();
$table->index(['status', 'published_at']);
});
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('parent_id')->nullable()->constrained('comments')->cascadeOnDelete();
$table->text('body');
$table->timestamps();
$table->index(['post_id', 'created_at']);
});