Build Comment And Reply System Using Only Comment Table In Laravel - FreeCodeBlog

Last updated: Dec 11, 2021

Today I will explain, how we can create a multilevel nested comment and reply system in laravel using only comment table. No need to create reply model, table, database to build nested comment system.

 

 

Laravel To Build Comment & Reply System.

I have a installed laravel project to build comment and reply system. If you haven't installed laravel project or don't know how to install laravel then read how to install any kind of laravel version tutorial.

 

Now you need to create post model, migration and controller.

 

php artisan make:model Post -mrc

 

Open post migration and add some filed.

 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onUpdate('cascade')->onDelete('cascade');
            $table->string('title')->unique();
            $table->string('slug')->unique();
            $table->longText('desc');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

 

You can create comment model and migration before configuration post model, controller.

 

php artisan make:model Comment -m

 

Next open post model and add relationship with user and comment model. 

 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'title', 'slug', 'desc',];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class)->whereNull('parent_id');
    }
}

 

Open comment migration and add some filed.

 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onUpdate('cascade')->onDelete('cascade');
            $table->foreignId('post_id')->constrained('posts')->onUpdate('cascade')->onDelete('cascade');
            $table->integer('parent_id')->nullable();
            $table->text('desc');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}

 

Add post and comment relationship in user model.

 

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
 

 

Next open comment model and add post, user, replies relationship.

 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'post_id', 'desc',];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }

}

 

I hope this tutorial help you to make a nested comment and reply system in laravel.

 

Okay so this is for today. See you again next tutorials. Thanks

Post Tags
Post Writer
masum7323
Masum Biswas (@masum7323)

My name is Masum Biswas. I'm a full stack developer. I live in Bangladesh and I love to write tutorials and tools that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, MySQL, VueJS, Tailwind CSS and Bootstrap from the early stage.

Follow Me On
Related Posts
How To Install Any Kind Of Laravel Version

Welcome to laravel. Want to install laravel version on your environment (windows 10, cpanel)? Yes!. Okay After reading this tutorial you can easily... Read More

Laravel Mail Configuration On Shared Hosting Cpanel

Want to configuration laravel mail on cpanel shared hosting? Actually after successfully deploy laravel project on shared hosting cpanel you need t... Read More

Laravel Jetstream User Email Verification Full Tutorial

Laravel jetstream user email verification! really? Yes, it's true that you can easily make laravel jetstream email verification. Do you want to cre... Read More

Upload Laravel Project To Shared Hosting Using Public Github Repository

Want to use GitHub public repository to upload laravel project to shared hosting cpanel? Public GitHub repository for laravel project uploading on... Read More

Download A File In Laravel Vue From Storage Folder

Want to download a file from storage folder in laravel with vue js? Yes! Okay don't worry you can easily make a download file from storage folder s... Read More