'500 Internal Server Error on Ajax request. Not sure the origin of the problem

I'm getting 500 Internal Server Error and I can't figure out the origin of the problem. This request is supposed to delete a comment with a certain id from the database. The id is passed using a hidden input. Here's my code:

My form:

<form method='POST' action=''>
    <input type="hidden" name="comment_id" value="{{ $comment->id }}">
    {{ csrf_field() }}
    {{ method_field('delete') }}
    <button class='submit-btn delete-comment' type='submit' name='commentDelete'>X</button>
</form>

<script>
    var urlDeleteComment = '{{ route('deleteComment') }}';
</script>

My route:

Route::delete('/comment', 'CommentsController@deleteComment')->name('deleteComment');

My JavaScript:

$('.delete-comment').on('click', function(event) {
    event.preventDefault();
    var commentId = $("input[name=comment_id]").val();

    $.ajax({
        method: 'POST',
        url: urlDeleteComment,
        data: {
            commentId: commentId,
            _token: token
        }
    }).done(function(response) {

    })
});

My PHP:

public function deleteComment(Request $request){
    $commentId = $request['commentId'];
    $comment = Comment::find($commentId);
    $comment->delete();
}

After I use console.log(commentId) in the JavaScript, I get the id of the number so it seems that I am successfully getting it. Sadly I'm not sure how to troubleshoot the 500 Internal Server Error. I just know that it is a server side error but I can't figure out what is it.

I checked the logs and saw this error:

[2018-12-20 22:12:23] local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `comments` (`user_id`, `image_id`, `comment`, `updated_at`, `created_at`) values (, , , 2018-12-20 22:12:23, 2018-12-20 22:12:23)) 
{"userId":1,"email":"[email protected]","exception":"[object] (Illuminate\\Database\\QueryException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `comments`
(`user_id`, `image_id`, `comment`, `updated_at`, `created_at`) values (, , , 2018-12-20 22:12:23, 2018-12-20 22:12:23)) at C:\\MAMP\\htdocs\\Art\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:664,
PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null at C:\\MAMP\\htdocs\\Art\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:458)
[stacktrace]

Now the weird thing is that this is not even part of the deleteComment() function but rather than part of a previous function called postComment(). Here is the full PHP code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\Image;

class CommentsController extends Controller
{
    public function postComment(Request $request){
        $userId = $request['userId'];
        $imageId = $request['imageId'];
        $commentText = $request['comment'];
        $image = Image::with('user')->find($imageId);

        $comment = new Comment();
        $comment->user_id = $userId;
        $comment->image_id = $imageId;
        $comment->comment = $commentText;
        $comment->save();

        $image->updateComments();

        return response()->json(['comment'=>$comment, 'image'=>$image]);
    }

    public function deleteComment(Request $request){
        $commentId = $request['commentId'];
        $comment = Comment::find($commentId);
        $comment->delete();
    }
}


Solution 1:[1]

For your delete endpoint your ajax call should look like:

$.ajax({
    method: 'POST',
    url: urlDeleteComment,
    data: {
        commentId: commentId,
        _method: 'DELETE',
        _token: token
    }
}).done(function(response) {

})

Solution 2:[2]

Try to use this code

<form method='POST' id='delete_comment'>
    <input type="hidden" name="comment_id" value="{{ $comment->id }}">
    @csrf
    <div id="status" style="display: none;"></div>
    <button class='submit-btn delete-comment' type='submit' name='commentDelete'>X</button>
</form>

Route:

// POST 
Route::post('/comment/delete', 'CommentsController@deleteComment')->name('deleteComment');

JavaScript:

<script type="text/javascript">  
$(document).ready(function(){

 $('#delete_comment').on('submit', function(event){
  event.preventDefault();
  // ADD WAIT CSS IF YOU WANT HERE :) 
  $.ajax({
   url:"{{ route('deleteComment') }}",
   method:"POST",
   data: new FormData(this),
   // DATA RETURN JSON
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   success:function(data)
   {
    // REMOVE YOUR WAIT CSS BEFORE SHOW YOUR SUCCESS MSG

    // SHOW SUCCESS OR WARNING MSG
    jQuery('#status').toggle('show');
    $('#status').addClass(data.status);
    $('#status').innerHTML = data.msg;
   },
   error: function(data) {
    console.log(data);
   }
   });
 });

});
</script>

Controller:

<?php
protected function deleteComment(Request $request){
    // NOT GIVE ANY ONE TO DELETE YOUR COMMNET 
    $comment = Comment::find($request->comment_id);
    // CHECK IF IS COMMNET IN DATABASE :) 
    if ($comment) {
        $comment->delete();
        return response()->json([
            'msg' => 'success', 
            'status' => 'alert alert-success'
        ]);
    }
    return response()->json([
        'msg' => 'error, not found', 
        'status' => 'alert alert-danger'
    ]);
}

?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 adam
Solution 2