首页 > 解决方案 > Laravel/Ajax DELETE:“在 null 上调用成员函数 delete()”

问题描述

正如标题所说,当我尝试使用 laravel/ajax 和控制器内部的函数删除我的数据时出现错误:

1

控制器:

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

}

表单和阿贾克斯:

`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::delete('/bbr-category-configuration-delete/{category_id}', [BBRCategoryConfigurationController::class,'destroy']);

注意事项:

删除按钮的第二个 ajax 函数:$(document).on('click', '.delete_category_btn', function (e),我还尝试显示 id,alert(cat_id);以证明 id 在模态中仍然被识别:

2

即使 category_id 存在,在尝试删除后检查页面仍然显示:

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

我能做些什么来解决这个问题?谢谢你的帮助。

标签: ajaxlaravelcontrollersql-deletehttp-status-code-500

解决方案


$category_delete对象为空。也许你发错了$category_id。如果您在删除之前检查该类别是否存在,则可以避免该错误。

public function destroy($category_id) {
    $category_delete = HmsBbrCategory::find($category_id);

    if($category_delete) {
        $category_delete->delete();
        return response()->json([
            'status'=>200,
            'message'=>'Category Deleted!',
        ]);
    }
    
    return response()->json([
        'status'=>404,
        'message'=>'Category Not Found!',
    ]);
}

推荐阅读