Laravel commenting with ajax

So I have a laravel commenting system which lets me conment using ajax. My current setup is simple. I have a field for comments and then my route is as follows:

Route::post(‘comment/{post_id}’, ‘CommentController@insert’);

And in my ajax url, I have given the same route with the post_id. I am giving the post id because I wanted to add the post id to my post_id column in my comments table. Also my ajax is in line.

Now my question is, I do not know how to add replies to a comment. I have to insert the comment_id to my replies table comment_id column because comment and replies are related. What confuses me is, if I created a lot of reply forms with a foreach loop for each comment, how can I pass all those comment ID to the ajax? Say for an example this is my route for storing replies

Route::post(‘replies/{comment_id}’, ‘ReplyController@insert’);

This won’t be like comments that I will be passing only value for the parameter (post_id). This reply will have a lot of values for one parameter right? So how can I proceed with this. I am new to ajax and I am having a hard time trying to get the logic of this. Like I mentioned before, the confusion is that each reply will have a separate comment_id that I need to pass to the route parameter.

4 answers

  • answered 2018-07-11 03:57 Minar Mnr

    You have to pass post_id during reply .

    Route like :

    Route::`post(‘replies/{post_id}/{comment_id}’, ‘ReplyController@insert’);`

    Then sort it those comment by inserting time .

  • answered 2018-07-11 04:32 SpreadYourWings

    you should pass like below:


  • answered 2018-07-11 06:09 rkj

    You can try like this

    View (here $comments and $comment->replies are assumed, you may have different)

    <div class="post-comments">
         @foreach($comments as $comment)
              @foreach($comment->replies as $reply)
               <form name="replyForm">
                   <input name="reply" />
                   <button type="button" onclick="replyComment('/comment/{{$comment->id}}/reply', this.form.reply)">Reply</button>


    function replyComment(url, input){
       //call ajax with this url and input value


    Route::post('comment/{comment_id}/reply', 'ReplyController@insert);

  • answered 2018-07-11 06:27 SpreadYourWings

    <input type="submit" style="float: right;" class="btn btn-primary" value="Comment" id="comment" data-url="/comment/{{$comment->id}}/replies" data-token="{{ csrf_token() }}" data-comment_id="{{$comment->id}}" >

    assuming that you are fetching the $comment from controller. even if you are adding button there is no need to add the <form>.