Comment tutorial using Scratch in Laravel.

commnets

In this tutorial, I’ll explain how to create a comment tutorial using Scratch in Laravel.

A Comment system is mainly required for blog websites or another website that provides customer services. In this post, I want to share with you how to create a comments system for your laravel project.

We will explain a very easy Comment system tutorial, you can easily add or reply to your comment using laravel relationships.

You have to find the Blog Theme for Laravel and ingrate it in your project. And Create Post Create edit, update and delete. in your Project

If you have any doubts about how to create a Post in laravel you can see my previous tutorial Laravel CRUD Operation for a beginner with example and demo.


Post View Page:


Post List Page:


Step 1: Install Latest Laravel

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

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

If you already create Project and CRUD operation on your Post then you don’t have to create a new project. You can use your old project.


Step 2: Create a Comment Table and database migration.

In this step, we create database tables, so open your terminal and run this below command.

php artisan make:migration create_comments_table

After these commands perform you have to open {Project Name}/database/migration and put below code.

<?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('comments', function (Blueprint $table) {
            $table->increments('comments_id');
            $table->integer('user_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->integer('parent_id')->unsigned()->nullable();
            $table->text('body');
            $table->timestamps();
        });
    }

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

Now you have to run this migration by the following command:

php artisan migrate

Step 3: Create Model & Controller

In this step we have to create Controller & Model, so open your terminal and run below command.

php artisan make:controller CommentController --resource --model=Comment

After this Command, we have to create seven methods in laravel.

  • storeComment => This method uses for store data in the database.
  • replyCommnet => This method uses for reply message stores in the database.

In this step, we have to find app/Http/Controllers/CommentController.php and put the below code.

<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Comment;
use App\Post;
use Auth;

class CommentController extends Controller{
    public function storeComment(Request $request){
        $comment = new Comment;
        $comment->body = $request->get('body');
        $comment->user()->associate($request->user());
        $post = Post::find($request->get('post_id'));
        $post->comments()->save($comment);
        return back();
    }
    public function replyCommnet(Request $request){
        $reply = new Comment();
        $reply->body = $request->get('body');
        $reply->user()->associate($request->user());
        $reply->parent_id = $request->get('comments_id');
        $post = Post::find($request->get('post_id'));
        $post->comments()->save($reply);
        return back();
    }
}

In this step, we have to find app/Commnet.php and put the below code.

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Comment extends Model
{
    protected $fillable = ['user_id', 'post_id', 'parent_id', 'body'];

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

    public function showComment(){
    	return self::join('users', 'users.id', '=', 'comments.user_id')
             		->select('comments.*', 'comments.id','comments.body'
                        	,'comments.created_at','users.name')
             		->get();
    }
     public function replies(){
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

In this step, we have to find app/Post.php and put the below code.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model implements Searchable
{
    protected $fillable = ['title', 'body'];
    public function comments(){
        return $this->hasMany(Comment::class)->whereNull('parent_id');
    }
}

Step 4: Create a route


In this step, we have to find routes/web.php and put the below code.

Route::post('comment/add', 'CommentController@storeComment')->name('comment/add');
Route::post('reply/add', 'CommentController@replyCommnet')->name('reply/add')

Step 5: Create blade files


In this step, we have to find resources/views and create a new folder name post & put the below code.

First, you have had to create commentShow.blade.php

@foreach($comments as $comment)
    @if(Auth::User()->id == $comment->user_id)
        <div class="row">
            <div class="col-md-12">
                <div class="display-comment">
                        <h5 class="" style="text-align: right;">{{ $comment->user->name }}</h5>
                        <p class="" style="margin-bottom: unset;">{{ $comment->body }}</p>
                </div>
            </div>
        </div>
    </br>
        @else
        <div class="row">
            <div class="col-md-12">
                <div class="display-comment1">
                    <h5 class="" style="text-align: right;">{{ $comment->user->name }}</h5>
                    <p class="" style="margin-bottom: unset;">{{ $comment->body }}</p>
                </div>
            </div>
        </div>
    @endif
        <style type="text/css">
            .display-comment  {
                background-color: #E6E6FA;
                color: #000000 !important;
                width: 46%;
                float: right;
                /*height: auto;*/
                padding: 10px 25px;
            }
            .display-comment1  {
                background-color: bisque;
                color: #000000 !important;
                width: 46%;
                float: left;
                margin: 10px -1rem;
                /*height: auto;*/
                padding: 10px 25px;
            }
            h5 {
                color: #000000;
            }
        </style>
@endforeach

When you have already created POST (Edit, Update, Delete & Read) then you have to already create show.blade.php file so you have put code on this file.

@extends('layouts.app') 
@section('content')
<div class="container" style="margin-top: 20px;">
    <div class="row justify-content-center">
        <div class="col-lg-10 card-header">
            <div class="row">
                <div class="col-md-10">
                    <h6>Show Your Post</h6>
                </div>
                <div class="col-md-2 pull-right">
                    <a class="btn btn-success" href="{{ route('posts') }}">
                        <div class="text-right">Back</div>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <br/>
    <div class="row justify-content-center ">
        <div class="col-lg-10 card">
            <div class="card-body">
                <div class="text-center">
                    <h6>Posted on {{ $post->created_at }}</h6>
                </div>
                <img src="{{ route('blog_image_display', [$post['files']]) }}" alt="{{ $post['files'] }}" height="450px" width="750px" />
                </br>
                </br>
                <div class="text-center">
                    <h4>Title:{{ $post->title }}</h4>
                </div>
                </br>
                <div class="text-center">
                    <h3>Content:</h3>
                </div>
                <div class="text-center">{!! $post->body !!}</div>
                </br>
                <div class="author col-md-12" >
                    <h4>Author:{{ $user->name }}</h4>
                </div>
                <div class="row">
                    <div class="category col-md-12" style="margin: 15px;">
                        <h4>Category:</h4 >
                        @foreach($category as $category_id => $category_name)
                            <a href="{{ route('posts/category',$category_id) }}" class="btn btn-primary">{{ $category_name }}</a>
                        @endforeach
                    </div>
                    <div class="tag col-md-12" style="margin: 15px;">
                        <h4>Tag:</h4>
                        @foreach($tag as $tag_id => $tag_name)
                            <a href="{{ route('posts/tags', $tag_id) }}" class="btn btn-primary">{{ $tag_name }}</a>
                        @endforeach
                    </div>
                </div>
                </br>
                <hr />
                <div class="    " style="padding: 0px 30px; width: auto;">
                    <h4>Show Comments</h4>
                    @include('Admin.posts.commentsDisplay', ['comments' => $post->comments, 'post_id' => $post->id])
                </div>
            </div>
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="col-lg-10 card-header1">
            <div class="row">
                <div class="col-md-10">
                    <h6>Add comment</h6>
                    <form method="post" action="{{ route('comment/add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <br/>
</div>
<style type="text/css">
    .card-header {
    border-radius: .625rem !important;
    box-shadow: 0 0.46875rem 2.1875rem rgba(90,97,105,.1), 
    0 0.9375rem 1.40625rem rgba(90,97,105,.1), 
    0 0.25rem 0.53125rem rgba(90,97,105,.12), 
    0 0.125rem 0.1875rem rgba(90,97,105,.1);
    }
    .card-header1 {
    border-radius: .625rem !important;
    box-shadow: 0 0.46875rem 2.1875rem rgba(90,97,105,.1), 
    0 0.9375rem 1.40625rem rgba(90,97,105,.1), 
    0 0.25rem 0.53125rem rgba(90,97,105,.12), 
    0 0.125rem 0.1875rem rgba(90,97,105,.1);
    margin-top: 20px;
    padding: 20px;
    background-color: white;
    }
</style>
@endsection

Now we are ready to run our task with laravel , so run bellow command for the run:

php artisan serve

Now you have to open your browser and put below URL:

http://localhost:8000/posts

About Dhaval Shah

My name is Dhaval Shah. I'm a PHP developer, entrepreneur and CEO of DAG inventions PVT ltd. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress and Bootstrap.
Follow me on Github / Linkedin

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!