Laravel AJAX Post引用表上的ID

时间:2016-05-26 04:54:09

标签: laravel laravel-5.2

这必须是一个基本问题。我有一个post请求从数据库表中删除记录,但它没有删除。这是因为在我的AJAX请求和URL中,我引用了表中记录的ID,但是控制器方法没有将此变量与ID列相关联。

JS:

$ notificationId是数据库表中该记录的呈现ID。

$('.remove-notification').click(function(e){
    e.preventDefault();
    $userUsername = $('.user-username').text();
    $notificationId = $(this).parent().siblings('.notification-id').text();
    $.ajax({
        type: "POST",
        url: "/"+$userUsername+"/notifications/delete/"+$notificationId,
        error: function(data){
            /*Retrieve errors and append any error messages.*/
            var errors = $.parseJSON(data.responseText);
            console.log(errors);
        },
        success: function(data){
            console.log(data);
        }
    });
});

控制器:

public function postDeleteNotification(Request $request, $id)
{
    if ($request->ajax())
    {
        DB::table('notifications_user')
        ->where('user_id', Auth::user()->id)
        ->where('id', $id)
        ->delete();
    }
}

请求处理没有任何错误,请求的URL在控制台中看起来很好。如果我删除“ - > where('id',$ id)”,那么基本的删除方法有效,所以我知道这是where语句的问题。任何帮助表示赞赏。谢谢!

更新:

Route::post('/{username}/notifications/confirm', [
    'uses' => '\App\Http\Controllers\NotificationController@postConfirmNotifications',
    'middleware' => ['auth'],
]);

Route::post('/{username}/notifications/delete/{notificationId}', [
    'uses' => '\App\Http\Controllers\NotificationController@postDeleteNotification',
    'middleware' => ['auth'],
]);

Route::post('/{username}/notifications/all/delete', [
    'uses' => '\App\Http\Controllers\NotificationController@postDeleteNotificationAll',
    'middleware' => ['auth'],
]);

1 个答案:

答案 0 :(得分:1)

我只是想知道你的方法应该是什么样的

public function postDeleteNotification(Request $request,$username, $id)
{
    if ($request->ajax())
    {
        DB::table('notifications_user')
        ->where('user_id', Auth::user()->id)
        ->where('id', $id)
        ->delete();
    }
}
相关问题