Laravel Comment System Tutorial Example

By Hardik Savani April 16, 2024 Category : PHP Laravel

A Comment system is a primary requirement for blog website or any tutorial website. in this post i want to share with you how to create comments system in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 app. Most of developer looking for good package for comment system, but if you are using laravel 5 then you can do it nested comment system using database relationship.

we will create very simple comment system with you can add comment and make replay to comment. we will use laravel relationship for comment system and it make it quick. you can also improve with add comment, edit comment, delete command and replay comment with ajax if you want.

After following this tutorial, you do not need to use any extra plugin for comment like disqus etc in your website.

in this example, we will create posts table and comments table using migration. you can create new post and in the detail page of post you can add comment on it. we will create laravel auth, create migration, controller, model and blade files. you just need to follow few steps to get live comment system with your website.

Post Detail Page:

Post Page:

Step 1 : Install Laravel 5.7

first of all we need to get fresh Laravel 5.7 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Update Database Configuration

In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 5.7. So let's open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3: Create Post and Comment Table

we are going to create comment system from scratch. so we have to create migration for "posts" and "comments" table using Laravel 5.7 php artisan command, so first fire bellow command:

php artisan make:migration create_posts_comments_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create tables.

<?php

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

class CreatePostsCommentsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('body');

$table->timestamps();

$table->softDeletes();

});

Schema::create('comments', function (Blueprint $table) {

$table->increments('id');

$table->integer('user_id')->unsigned();

$table->integer('post_id')->unsigned();

$table->integer('parent_id')->unsigned()->nullable();

$table->text('body');

$table->timestamps();

$table->softDeletes();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

Schema::dropIfExists('comments');

}

}

Now you have to run this migration by following command:

php artisan migrate

Step 4: Create Auth

in this step, we need to create laravel auth scaffolding using auth command. laravel provide default user authentication. so simply run bellow command:

php artisan make:auth

Step 5: Create Model

In this step, we need to create model Post and Comment for each table. we also need to make code for laravel relationship for comments, replies, user. So create both model as bellow.

Run bellow command to create Post model:

php artisan make:model Post

app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model

{

use SoftDeletes;

protected $dates = ['deleted_at'];

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = ['title', 'body'];

/**

* The has Many Relationship

*

* @var array

*/

public function comments()

{

return $this->hasMany(Comment::class)->whereNull('parent_id');

}

}

Run bellow command to create Comment model:

php artisan make:model Comment

app/Comment.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Comment extends Model

{

use SoftDeletes;

protected $dates = ['deleted_at'];

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = ['user_id', 'post_id', 'parent_id', 'body'];

/**

* The belongs to Relationship

*

* @var array

*/

public function user()

{

return $this->belongsTo(User::class);

}

/**

* The has Many Relationship

*

* @var array

*/

public function replies()

{

return $this->hasMany(Comment::class, 'parent_id');

}

}

Step 6: Create Controller

In this step, now we should create new controller as PostController and CommentController. So run bellow command and create new controller. bellow controller for create resource controller.

Create Post Controller using bellow command:

php artisan make:controller PostController

app/Http/Controllers

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;

class PostController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$posts = Post::all();

return view('posts.index', compact('posts'));

}

/**

* Show the form for creating a new resource.

*

* @return \Illuminate\Http\Response

*/

public function create()

{

return view('posts.create');

}

/**

* Store a newly created resource in storage.

*

* @param \Illuminate\Http\Request $request

* @return \Illuminate\Http\Response

*/

public function store(Request $request)

{

$request->validate([

'title'=>'required',

'body'=>'required',

]);

Post::create($request->all());

return redirect()->route('posts.index');

}

/**

* Show the form for creating a new resource.

*

* @return \Illuminate\Http\Response

*/

public function show($id)

{

$post = Post::find($id);

return view('posts.show', compact('post'));

}

}

Create Post Controller using bellow command:

php artisan make:controller CommentController

app/Http/CommentController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Comment;

class CommentController extends Controller

{

/**

* Store a newly created resource in storage.

*

* @param \Illuminate\Http\Request $request

* @return \Illuminate\Http\Response

*/

public function store(Request $request)

{

$request->validate([

'body'=>'required',

]);

$input = $request->all();

$input['user_id'] = auth()->user()->id;

Comment::create($input);

return back();

}

}

Step 7: Create Blade Files

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "posts" then create blade files for comment system. So finally you have to create following bellow blade file:

1) index.blade.php

2) show.blade.php

3) create.blade.php

4) commentsDisplay.blade.php

resources/views/posts/index.blade.php

@extends('layouts.app')

@section('content')

<div class="container">

<div class="row justify-content-center">

<div class="col-md-12">

<h1>Manage Posts</h1>

<a href="{{ route('posts.create') }}" class="btn btn-success" style="float: right">Create Post</a>

<table class="table table-bordered">

<thead>

<th width="80px">Id</th>

<th>Title</th>

<th width="150px">Action</th>

</thead>

<tbody>

@foreach($posts as $post)

<tr>

<td>{{ $post->id }}</td>

<td>{{ $post->title }}</td>

<td>

<a href="{{ route('posts.show', $post->id) }}" class="btn btn-primary">View Post</a>

</td>

</tr>

@endforeach

</tbody>

</table>

</div>

</div>

</div>

@endsection

resources/views/posts/show.blade.php

@extends('layouts.app')

@section('content')

<div class="container">

<div class="row justify-content-center">

<div class="col-md-8">

<div class="card">

<div class="card-body">

<h3 class="text-center text-success">ItSolutionStuff.com</h3>

<br/>

<h2>{{ $post->title }}</h2>

<p>

{{ $post->body }}

</p>

<hr />

<h4>Display Comments</h4>

@include('posts.commentsDisplay', ['comments' => $post->comments, 'post_id' => $post->id])

<hr />

<h4>Add comment</h4>

<form method="post" action="{{ route('comments.store' ) }}">

@csrf

<div class="form-group">

<textarea class="form-control" name="body"></textarea>

<input type="hidden" name="post_id" value="{{ $post->id }}" />

</div>

<div class="form-group">

<input type="submit" class="btn btn-success" value="Add Comment" />

</div>

</form>

</div>

</div>

</div>

</div>

</div>

@endsection

resources/views/posts/create.blade.php

@extends('layouts.app')

@section('content')

<div class="container">

<div class="row justify-content-center">

<div class="col-md-8">

<div class="card">

<div class="card-header">Create Post</div>

<div class="card-body">

<form method="post" action="{{ route('posts.store') }}">

<div class="form-group">

@csrf

<label class="label">Post Title: </label>

<input type="text" name="title" class="form-control" required/>

</div>

<div class="form-group">

<label class="label">Post Body: </label>

<textarea name="body" rows="10" cols="30" class="form-control" required></textarea>

</div>

<div class="form-group">

<input type="submit" class="btn btn-success" />

</div>

</form>

</div>

</div>

</div>

</div>

</div>

@endsection

resources/views/posts/commentsDisplay.blade.php

@foreach($comments as $comment)

<div class="display-comment" @if($comment->parent_id != null) style="margin-left:40px;" @endif>

<strong>{{ $comment->user->name }}</strong>

<p>{{ $comment->body }}</p>

<a href="" id="reply"></a>

<form method="post" action="{{ route('comments.store') }}">

@csrf

<div class="form-group">

<input type="text" name="body" class="form-control" />

<input type="hidden" name="post_id" value="{{ $post_id }}" />

<input type="hidden" name="parent_id" value="{{ $comment->id }}" />

</div>

<div class="form-group">

<input type="submit" class="btn btn-warning" value="Reply" />

</div>

</form>

@include('posts.commentsDisplay', ['comments' => $comment->replies])

</div>

@endforeach

Now we are ready to run our comment system application example with laravel 5.7 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/posts

I hope it can help you....

Shares