Laravel: Comment on a Post using AJAX

Getting Started

This is a continuation of my previous tutorial, which you can visit, entitled Laravel User Post using AJAX.

Creating our Model

We will create our Comment model as well as our migration. 1. In command prompt, navigate to our project and type: php artisan make:model Comment -m This will create our model Comment.php located in app folder. It will also create the migration for us due to the -m that we added in creating the model located in database/migrations folder. It will be something like create_comments_table.php. 2. Since we are going to migrate this specific migration, we are going to transfer it to a folder so that the --path in our php artisan can locate this file. You can do this by creating a new folder in database/migration and name it as selected. 3. Open our transferred file and edit it with the ff codes:
  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateCommentsTable extends Migration
  8. {
  9.     /**
  10.      * Run the migrations.
  11.      *
  12.      * @return void
  13.      */
  14.     public function up()
  15.     {
  16.         Schema::create('comments', function (Blueprint $table) {
  17.             $table->increments('id');
  18.             $table->integer('userid');
  19.             $table->integer('postid');
  20.             $table->text('comment');
  21.             $table->timestamps();
  22.         });
  23.     }
  24.  
  25.     /**
  26.      * Reverse the migrations.
  27.      *
  28.      * @return void
  29.      */
  30.     public function down()
  31.     {
  32.         Schema::dropIfExists('comments');
  33.     }
  34. }

Migrating our Newly Created Migration

In command prompt, navigate to our project and type: php artisan migrate --path=/database/migrations/selected/ This will migrate all the files in our --path folder.

Updating our Routes

Next we update our routes to accommodate our comment function. This is our new web.php:
  1. <?php
  2.  
  3. Route::get('/', function () {
  4.     return view('welcome');
  5. });
  6.  
  7. Auth::routes();
  8.  
  9. Route::get('/home', 'HomeController@index')->name('home');
  10.  
  11. Route::post('/post', 'PostController@post');
  12.  
  13. Route::get('/show', 'PostController@getPost');
  14.  
  15. Route::get('/getcomment', 'PostController@getComment');
  16.  
  17. Route::post('/writecomment', 'PostController@makeComment');

Update and Create New Views

Update/Create the ff blades: home.blade.php
  1. @extends('layouts.app')
  2.  
  3. @section('content')
  4. <div class="container">
  5.     <h1 class="page-header text-center">Laravel User Post using AJAX</h1>
  6.     @if (session('status'))
  7.         <div class="alert alert-success">
  8.             {{ session('status') }}
  9.         </div>
  10.     @endif
  11.     <div class="row">
  12.         <div class="col-md-8 col-md-offset-2">
  13.             <div class="panel panel-default">
  14.                 <div class="panel-body">
  15.                     <form id="postForm">
  16.                         <textarea class="form-control" name="post" id="post" placeholder="What's on your mind?"></textarea>
  17.                         <button type="button" id="postBtn" class="btn btn-primary" style="margin-top:5px;"><i class="fa fa-pencil-square-o"></i> POST</button>
  18.                     </form>
  19.                 </div>
  20.             </div>
  21.             <div id="postList"></div>
  22.         </div>
  23.     </div>
  24. </div>
  25. @endsection
  26.  
  27. @section('script')
  28.     <script type="text/javascript">
  29.         $(document).ready(function(){
  30.             $.ajaxSetup({
  31.                 headers: {
  32.                     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  33.                 }
  34.             });
  35.  
  36.             showPost();
  37.  
  38.             $('#postBtn').click(function(){
  39.                 var post = $('#post').val();
  40.                 if(post==''){
  41.                     alert('Please write a Post first!');
  42.                     $('#post').focus();
  43.                 }
  44.                 else{
  45.                     var postForm = $('#postForm').serialize();
  46.                     $.ajax({
  47.                         type: 'POST',
  48.                         url: '/post',
  49.                         data: postForm,
  50.                         dataType: 'json',
  51.                         success: function(){
  52.                             showPost();
  53.                             $('#postForm')[0].reset();
  54.                         },
  55.                     });
  56.                 }
  57.             });
  58.  
  59.             $(document).on('click', '.comment', function(){
  60.                 var id = $(this).val();
  61.                 if($('#commentField_'+id).is(':visible')){
  62.                     $('#commentField_'+id).slideUp();
  63.                 }
  64.                 else{
  65.                     $('#commentField_'+id).slideDown();
  66.                     getComment(id);
  67.                 }
  68.             });
  69.  
  70.             $(document).on('click', '.submitComment', function(){
  71.                 var id = $(this).val();
  72.                 if($('#commenttext').val()==''){
  73.                     alert('Please write a Comment First!');
  74.                 }
  75.                 else{
  76.                     var commentForm = $('#commentForm_'+id).serialize();
  77.                     $.ajax({
  78.                         type: 'POST',
  79.                         url: 'writecomment',
  80.                         data: commentForm,
  81.                         success: function(){
  82.                             getComment(id);
  83.                             $('#commentForm_'+id)[0].reset();
  84.                         },
  85.                     });
  86.                 }
  87.                    
  88.             });
  89.          
  90.         });
  91.  
  92.         function showPost(){
  93.             $.ajax({
  94.                 url: '/show',
  95.                 success: function(data){
  96.                     $('#postList').html(data);
  97.                 },
  98.             });
  99.         }
  100.  
  101.         function getComment(id){
  102.             $.ajax({
  103.                 url: 'getcomment',
  104.                 data: {id:id},
  105.                 success: function(data){
  106.                     $('#comment_'+id).html(data);
  107.                 }
  108.             });
  109.         }
  110.     </script>
  111. @endsection

postlist.blade.php

  1. @foreach($posts as $post)
  2.         <div class="panel panel-default">
  3.                 <div class="panel-body">
  4.                         <p style="font-size:16px;"><b>{{ $post->name }}</b> added a post.</p>
  5.                         <p style="font-size:11px; margin-top:-10px;">{{ date('M d, Y h:i A', strtotime($post->created_at)) }}</p>
  6.                         <h3 style="padding-top:30px; padding-bottom:30px;">{{ $post->post }}</h3>
  7.                 </div>
  8.                 <div class="panel-footer">
  9.                         <div class="row">
  10.                                 <div class="col-md-2">
  11.                                         <button class="btn btn-primary btn-sm"><i class="fa fa-thumbs-up"></i> <span>Like</span></button>
  12.                                 </div>
  13.                                 <div class="col-md-10" style="margin-left:-40px;">
  14.                                         <button type="button" class="btn btn-primary btn-sm comment" value="{{ $post->postid }}"><i class="fa fa-comments"></i> Comment</button>
  15.                                 </div>
  16.                         </div>
  17.                 </div>
  18.         </div>
  19.         <div id="commentField_{{ $post->postid }}" class="panel panel-default" style="padding:10px; margin-top:-20px; display:none;">
  20.                 <div id="comment_{{ $post->postid }}">
  21.                 </div>
  22.                 <form id="commentForm_{{ $post->postid }}">
  23.                         <input type="hidden" value="{{ $post->postid }}" name="postid">
  24.                         <div class="row">
  25.                                 <div class="col-md-10">
  26.                                         <input type="text" name="commenttext" id="commenttext" data-id="{{ $post->postid }}" class="form-control commenttext" placeholder="Write a Comment...">
  27.                                 </div>
  28.                                 <div class="col-md-2" style="margin-left:-25px;">
  29.                                         <button type="button" class="btn btn-primary submitComment" value="{{ $post->postid }}"><i class="fa fa-comment"></i> Submit</button>
  30.                                 </div>
  31.                         </div>
  32.                        
  33.                 </form>
  34.         </div>
  35. @endforeach
commentlist.blade.php
  1. @foreach($comments as $comment)
  2.         <div >
  3.                 <b>{{ $comment->name }}</b>: {{ $comment->comment }}
  4.                 <p style="font-size:9px;">{{ date('M d, Y h:i A', strtotime($comment->created_at)) }}</p>
  5.         </div>
  6. @endforeach

Updating our Controller

Next, update our PostController.php with the ff:
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use DB;
  7. use Auth;
  8. use App\Post;
  9. use App\Comment;
  10.  
  11. class PostController extends Controller
  12. {
  13.     public function getPost(){
  14.         $posts = DB::table('posts')
  15.                         ->join('users', 'users.id', '=', 'posts.userid')
  16.                         ->select('posts.id as postid', 'posts.*', 'users.id as userid', 'users.*')
  17.                         ->orderBy('posts.created_at', 'desc')
  18.                         ->get();
  19.  
  20.                 return view('postlist', compact('posts'));
  21.     }
  22.  
  23.     public function post(Request $request){
  24.         if ($request->ajax()){
  25.                 $user = Auth::user();
  26.                 $post = new Post;
  27.  
  28.                 $post->userid = $user->id;
  29.                 $post->post = $request->input('post');
  30.  
  31.                         $post->save();
  32.                
  33.                 return response($post);
  34.         }
  35.     }
  36.  
  37.     public function getComment(Request $request){
  38.         if ($request->ajax()){
  39.            $comments = DB::table('comments')
  40.                     ->join('users', 'users.id', '=', 'comments.userid')
  41.                     ->select('comments.id as commentid', 'comments.*', 'users.id as userid', 'users.*')
  42.                     ->where('postid', '=', $request->id)
  43.                     ->get();
  44.  
  45.             return view('commentlist', compact('comments'));
  46.         }
  47.     }
  48.  
  49.     public function makeComment(Request $request){
  50.         if ($request->ajax()){
  51.             $user = Auth::user();
  52.             $comment = new Comment;
  53.  
  54.             $comment->userid = $user->id;
  55.             $comment->postid = $request->postid;
  56.             $comment->comment = $request->commenttext;
  57.  
  58.             $comment->save();
  59.  
  60.             return response($comment);
  61.         }
  62.     }
  63. }

Running our Server

In your web browser, type the name that you added in localhost for your project in my case, post.dev. You should now be able to comment on any post. That ends this tutorial. Happy Coding :)

Comments

good video

good

ho do you get that id parameters value in getComment function ?

Thanks

Add new comment