为什么没有在Laravel5.6中删除表中的用户

vktxenjb  于 2021-06-18  发布在  Mysql
关注(0)|答案(5)|浏览(404)

我正在使用Laravel5.6 delete 用户表中的用户作为管理员。我有下面的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确认通过后,接受它仍然不会删除记录。url更改如下:

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

我怎样才能解决这个问题?

h5qlskok

h5qlskok1#

你可以尝试像这样的方法

User::destroy($id)
4bbkushb

4bbkushb2#

在你的 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'); 
}
unftdfkk

unftdfkk3#

将路线改为:

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

然后检查数据库表是否已删除用户。如果不是,那么我认为这是您的数据库中的ci冲突,仅仅因为一个用户id是另一个表中的外键,您就不能删除它。

sauutmhj

sauutmhj4#

我会改变你的想法 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'); 
}
mznpcxlj

mznpcxlj5#

将路线改为:

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

更改以下行:

<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>

<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>

相关问题