Deleting Comments Using AJAX

In a previous article, Posting Comments Using AJAX, a covered how to allow for comments to be posted to topics/articles in your Laravel based CMS using Jquery/AJAX. In this second part I am covering how to delete comments.  The code is very similar, however, the major difference is the requirement of an authenticated user. 

Let's get down to it then.  We'll start off with the route:


  Route::post('/post/deleteComment', ['as' => 'deleteComment', 'uses'=>'PostsController@deleteComment']); 

That was easy right?

Now we move on to the controller. We could create a Comments controller, and likely should, however, I have taken the lazy route here as I only have a couple of functions related to posts and have placed those in the PostsController:

   public function deleteComment() {

        $comment = Comments::find(Input::get("id"))->firstOrFail();
        if ($comment->delete()) {
            return json_encode(["success"=>"Comment removed."]);

        } else {
            return json_encode(["error"=>"Error deleting comment"]);
public function postComment(){ $comment = new Comments(); $comment->posts_id = Input::get("postId"); $comment->email = Input::get("email"); $comment->name = Input::get('name'); $comment->comment = Input::get("comment"); if ($comment->save()){ return json_encode($comment); }else { return json_encode(["error"=>"Error saving comment"]); } }

You will notice that the deleteComment function takes no variable/parameters.  We could simplify the delete method considerably with a little help from a friend. Alright, sorry, no more pop music references.  So, if we do some route binding we could pass in a Comment model as parameter and get right to the delete. 


    Route::bind('comment', function ($id){
    return App\Comments::find($id)->firstOrFail();

In the above we are telling the router to automatically find and load the first Comment record found with the id being passed in. I use a similar route binding for posts to produce the pretty urls. With the above binding we can then simplify the deleteComment method to:


    public function deleteComment(Comments $comment) {
        if ($comment->delete()){
            return json_encode(["success"=>"Comment removed."]);

        } else {
            return json_encode(["error"=>"Error deleting comment"]);

Ok so now on to the view and the Jquery/AJAX code. We will have a method to delete, a simple if statement to display the delete icon for authenticated users.  


    //If statement to display the delete icon.
<div class="panel-heading cmsPanelHeading">Edit Post @if(!Auth::guest()) <i onclick="removeComment($('#commentId').val())" class="glyphicon glyphicon-remove pull-right" aria-hidden="true"></i>@endif

So we're displaying the <i> element here when the user is logged in and then we're using jquery to pull in the id from the Comments model passed in via Laravel, which is a hidden element with an id of "commentId". When this element is clicked it will call the below removeComment function. 


   function removeComment(commentId) {
                url: "/post/deleteComment/"+commentId,
                method: "post",
                data: {_token: $("input[name=_token]").val()},
                success: function (data) {
                    oldCLink = $('#totalComments').text();
                    i = oldCLink.indexOf(" ");
                    j = oldCLink.substr(0, i);
                    $('#totalComments').text(j + " Comments");

So to wrap it all up, the removeComent javascript function makes an AJAX call to the /post/deleteComment/{comment}, which is auto bound to a comment object and then passed to the PostsController, which then executes the delete. Pretty simple, eh? Don't you just love developing in Laravel and AJAX?


Post Comment