Laravel/Ajax DELETE: "Call to a member function delete() on null"

As the title says, I am getting an error when I try to delete my data using laravel/ajax and the function inside the controller:

1

Controller:

public function destroy($category_id) {
    $category_delete = HmsBbrCategory::find($category_id);
    $category_delete->delete();
    return response()->json([
        'status'=>200,
        'message'=>'Category Deleted!',
    ]);

}

Form & Ajax:

`delete_category` is the id that opens the delete modal and `delete_category_btn` is the button that will delete the data.

<button type="submit" class="btn btn-primary btn-block delete_category_btn"></i>Yes</button>
<button type="button" value="${cat.category_id}" class="delete_category btn btn-outline-secondary"><i class="fas fa-trash"></i> Delete</button>


        $(document).on('click', '.delete_category', function (e) {
            e.preventDefault();
            //click this button(delete_category) to get the value(category_id)
            var cat_id = $(this).val(); 
            // alert(cat_id);
            $('#delete_cat_id').val(cat_id);
            $('#deleteCategoryModal').modal('show');
        });
        $(document).on('click', '.delete_category_btn', function (e) {
            e.preventDefault();
            var cat_id = $('#delete_cat_id').val();
            // alert(cat_id);
            //token taken from laravel documentation
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                type: "DELETE",
                url: "/clinical/bbr-category-configuration-delete/"+cat_id,
                dataType: "dataType",
                success: function (response){
                    // console.log(response);
                    $('#category_notif').addClass('alert alert-success');
                    $('#category_notif').text(response.message);
                    $('#deleteCategoryModal').modal('hide');
                }
            });
        });

Route:

Route::delete('/bbr-category-configuration-delete/{category_id}', [BBRCategoryConfigurationController::class,'destroy']);

Things to note:

  • I went ahead and showed the category_id inside the modal to prove that the table is getting retrieved.

the the second ajax function for the delete button: $(document).on('click', '.delete_category_btn', function (e), I also tried to show the id using alert(cat_id); to also prove that the id is still getting recognized inside the modal:

2

Even if category_id is present, inspecting the page after attempting to delete still shows:

message: "Call to a member function delete() on null"

What can I do to resolve this? thanks for any help.

Source: Laravel

Leave a Reply