【问题标题】:Laravel AJAX Post Referencing ID on TableLaravel AJAX 在表上发布引用 ID
【发布时间】:2016-05-26 13:39:59
【问题描述】:

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

JS:

$notificationId 是该记录在 DB 表中的呈现 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'],
]);

【问题讨论】:

  • 死掉并转储 sql 查询,让我们看看你得到了什么!
  • 我如何通过 AJAX 请求做到这一点?
  • 你只需要把DB::enableQuerylog()放在查询之前和dd( DB::getQuerylog() )之后;
  • 我不认为你可以在 ajax 请求中做 Auth::user
  • Auth::user 确实有效,因为如果我删除第二个 where 子句,它就可以正常工作。

标签: laravel laravel-5.2


【解决方案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();
    }
}

【讨论】:

  • @MattPierce 很高兴它有帮助!
猜你喜欢
  • 2018-09-07
  • 2014-06-08
  • 1970-01-01
  • 2015-12-04
  • 2019-05-22
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
相关资源
最近更新 更多