为什么没有在Laravel 5.6中删除表中的用户

时间:2018-11-30 11:12:42

标签: php mysql laravel-5 controller

我正在使用Laravel 5.6,并将delete个用户从users表中用作admin。我具有以下 UserController 函数来删除表记录吗?

public function delete($id)
{
    User::where('id', $id)->delete();

    return redirect()
              ->back()
              ->with('info', 'User deleted successfully'); 
}

“我的用户”数据显示在索引刀片文件中,并带有如下删除按钮:

<td>
    <a class="button is-outlined" 
      href="{{route('users.index', $user->id.'/delete/')}}" 
      onclick="return confirm('Are you sure to want to delete this record?')"
     >
        Delete
     </a>
</td>

我的删除路线是这样的

Route::get('users/{users}/delete', [
    'uses' => '\App\Http\Controllers\UserController@delete',
]);

但现在我单击删除按钮javascript 确认通过,并且接受后仍然不会删除记录。网址更改如下:

http://localhost:8000/users?16/delete/     //16 is user id

如何解决此问题?

5 个答案:

答案 0 :(得分:1)

将路线更改为:

pids

更改以下行:

Route::get('users/{id}/delete', [
    'as' => 'users.delete','uses' => '\App\Http\Controllers\UserController@delete',
]);

TO

<td><a class="button is-outlined" href="{{route('users.index', $user->id.'/delete/')}}" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a></td>

答案 1 :(得分:0)

您可以尝试销毁类似的方法

User::destroy($id)

答案 2 :(得分:0)

在您的web.php路由文件中,您通过了{users},而没有通过{id}

Route::get('users/{id}/delete', [
    'uses' => '\App\Http\Controllers\UserController@delete',
])->name('user.delete');

在刀片视图中:

<td><a class="button is-outlined" href="{{route('users.delete',['id' => $user->id])}}" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a></td>`

在您的控制器中:

public function delete($id)
{
        User::where('id', $id)->delete();
        // or you can use User::destroy($id);
        return redirect()->back()->with('info', 'User deleted successfully'); 
}

答案 3 :(得分:0)

将路线更改为:

Route::get('users/{id}/delete', [
    'uses' => '\App\Http\Controllers\UserController@delete',
]);

然后检查您的数据库表是否已删除该用户。 如果不是这样,那么我认为这是您数据库中的CI违规,仅因为用户ID是另一个表中的外键,您就不能删除它。

答案 4 :(得分:0)

我会将您的route.php file更改为一种更简单的方法,有助于您理解:

Route::get('users/{id}/delete', 'UserController@delete')
->where(['id', => '[0-9]+'])
->name('user.delete');

在上面的路线上,您已经确保它仅接受id是数字的请求。另外,您可以为路由命名,以简化代码结构,因此,如果以后进行更改,则无需继续在表单中进行更改

然后,您表单上的路线生成也会对其进行更改:

href="{{route('user.delete', ['id' => $user->id])}}"

然后您的控制器将更改为

public function delete($id)
{
    $user = User::find($id);

    //Having a hold on your user model makes it able to also delete any other relationship it might have, if you so wish
    $user->delete();

    return redirect()
              ->back()
              ->with('info', 'User deleted successfully'); 
}