Laravel: Comment on a Post using AJAX
Submitted by nurhodelta_17 on Thursday, November 30, 2017 - 13:56.
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:
- <?php
- use Illuminate\Support\Facades\Schema;
- use Illuminate\Database\Schema\Blueprint;
- use Illuminate\Database\Migrations\Migration;
- class CreateCommentsTable extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public function up()
- {
- Schema::create('comments', function (Blueprint $table) {
- $table->increments('id');
- $table->integer('userid');
- $table->integer('postid');
- $table->text('comment');
- $table->timestamps();
- });
- }
- /**
- * Reverse the migrations.
- *
- * @return void
- */
- public function down()
- {
- Schema::dropIfExists('comments');
- }
- }
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:- <?php
- Route::get('/', function () {
- return view('welcome');
- });
- Auth::routes();
- Route::get('/home', 'HomeController@index')->name('home');
- Route::post('/post', 'PostController@post');
- Route::get('/show', 'PostController@getPost');
- Route::get('/getcomment', 'PostController@getComment');
- Route::post('/writecomment', 'PostController@makeComment');
Update and Create New Views
Update/Create the ff blades: home.blade.php- @extends('layouts.app')
- @section('content')
- <div class="container">
- <h1 class="page-header text-center">Laravel User Post using AJAX</h1>
- @if (session('status'))
- <div class="alert alert-success">
- {{ session('status') }}
- </div>
- @endif
- <div class="row">
- <div class="col-md-8 col-md-offset-2">
- <div class="panel panel-default">
- <div class="panel-body">
- <form id="postForm">
- <textarea class="form-control" name="post" id="post" placeholder="What's on your mind?"></textarea>
- <button type="button" id="postBtn" class="btn btn-primary" style="margin-top:5px;"><i class="fa fa-pencil-square-o"></i> POST</button>
- </form>
- </div>
- </div>
- <div id="postList"></div>
- </div>
- </div>
- </div>
- @endsection
- @section('script')
- <script type="text/javascript">
- $(document).ready(function(){
- $.ajaxSetup({
- headers: {
- 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
- }
- });
- showPost();
- $('#postBtn').click(function(){
- var post = $('#post').val();
- if(post==''){
- alert('Please write a Post first!');
- $('#post').focus();
- }
- else{
- $.ajax({
- type: 'POST',
- url: '/post',
- data: postForm,
- dataType: 'json',
- success: function(){
- showPost();
- },
- });
- }
- });
- $(document).on('click', '.comment', function(){
- var id = $(this).val();
- if($('#commentField_'+id).is(':visible')){
- $('#commentField_'+id).slideUp();
- }
- else{
- $('#commentField_'+id).slideDown();
- getComment(id);
- }
- });
- $(document).on('click', '.submitComment', function(){
- var id = $(this).val();
- if($('#commenttext').val()==''){
- alert('Please write a Comment First!');
- }
- else{
- $.ajax({
- type: 'POST',
- url: 'writecomment',
- data: commentForm,
- success: function(){
- getComment(id);
- },
- });
- }
- });
- });
- function showPost(){
- $.ajax({
- url: '/show',
- success: function(data){
- $('#postList').html(data);
- },
- });
- }
- function getComment(id){
- $.ajax({
- url: 'getcomment',
- data: {id:id},
- success: function(data){
- $('#comment_'+id).html(data);
- }
- });
- }
- </script>
- @endsection
postlist.blade.php
- @foreach($posts as $post)
- <div class="panel panel-default">
- <div class="panel-body">
- <p style="font-size:16px;"><b>{{ $post->name }}</b> added a post.</p>
- <h3 style="padding-top:30px; padding-bottom:30px;">{{ $post->post }}</h3>
- </div>
- <div class="panel-footer">
- <div class="row">
- <div class="col-md-2">
- <button class="btn btn-primary btn-sm"><i class="fa fa-thumbs-up"></i> <span>Like</span></button>
- </div>
- <div class="col-md-10" style="margin-left:-40px;">
- <button type="button" class="btn btn-primary btn-sm comment" value="{{ $post->postid }}"><i class="fa fa-comments"></i> Comment</button>
- </div>
- </div>
- </div>
- </div>
- <div id="commentField_{{ $post->postid }}" class="panel panel-default" style="padding:10px; margin-top:-20px; display:none;">
- <div id="comment_{{ $post->postid }}">
- </div>
- <form id="commentForm_{{ $post->postid }}">
- <input type="hidden" value="{{ $post->postid }}" name="postid">
- <div class="row">
- <div class="col-md-10">
- <input type="text" name="commenttext" id="commenttext" data-id="{{ $post->postid }}" class="form-control commenttext" placeholder="Write a Comment...">
- </div>
- <div class="col-md-2" style="margin-left:-25px;">
- <button type="button" class="btn btn-primary submitComment" value="{{ $post->postid }}"><i class="fa fa-comment"></i> Submit</button>
- </div>
- </div>
- </form>
- </div>
- @endforeach
Updating our Controller
Next, update our PostController.php with the ff:- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use DB;
- use Auth;
- use App\Post;
- use App\Comment;
- class PostController extends Controller
- {
- public function getPost(){
- $posts = DB::table('posts')
- ->select('posts.id as postid', 'posts.*', 'users.id as userid', 'users.*')
- ->orderBy('posts.created_at', 'desc')
- ->get();
- }
- public function post(Request $request){
- if ($request->ajax()){
- $user = Auth::user();
- $post = new Post;
- $post->userid = $user->id;
- $post->post = $request->input('post');
- $post->save();
- return response($post);
- }
- }
- public function getComment(Request $request){
- if ($request->ajax()){
- $comments = DB::table('comments')
- ->select('comments.id as commentid', 'comments.*', 'users.id as userid', 'users.*')
- ->where('postid', '=', $request->id)
- ->get();
- }
- }
- public function makeComment(Request $request){
- if ($request->ajax()){
- $user = Auth::user();
- $comment = new Comment;
- $comment->userid = $user->id;
- $comment->postid = $request->postid;
- $comment->comment = $request->commenttext;
- $comment->save();
- return response($comment);
- }
- }
- }
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
Add new comment
- Add new comment
- 2151 views