如何在 Laravel 5.4 中强制删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44075173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:00:17  来源:igfitidea点击:

how to force delete in laravel 5.4

phplaravel

提问by Masum

I made a user management system with soft deletion and force deletion options. However, I'm having trouble getting the force deletion option to work.

我制作了一个带有软删除和强制删除选项的用户管理系统。但是,我无法使强制删除选项起作用。

The route:

路线:

Route::post('users/{user}/delete', 'UserController@forcedelete');

The relevant controller code:

相关控制器代码:

public function forcedelete(User $user)
{
     $user->forceDelete();
     return redirect('users/trash');
}

The view code:

视图代码:

<a href="{{ url('users/'.$user->id.'/delete') }}" 
   onclick="event.preventDefault(); document.getElementById('delete').submit();">
    <i class="fa fa-trash-o btn btn-danger btn-xs"></i>
</a>

<form id="delete" action="{{ url('users/'.$user->id.'/delete') }}" 
      method="POST" style="display: none;">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
</form>

The error that I'm getting is

我得到的错误是

 MethodNotAllowedHttpException in RouteCollection.php line 233:

Why is it not working, and how can I fix it?

为什么它不起作用,我该如何解决?

回答by Sandeesh

Try placing this route above your other user routes or user resource route. Also you're trying to use route model binding with a soft deleted model, which won't work. You need to use the id and delete it manually.

尝试将此路由置于其他用户路由或用户资源路由之上。此外,您还尝试将路由模型绑定与软删除模型结合使用,但这是行不通的。您需要使用该 id 并手动删除它。

public function forcedelete($id)
{
    User::where('id', $id)->forceDelete();
    return redirect('users/trash');
}

Edit: Also delete {{ method_field('DELETE') }}from your form, since the route method defined is post.

编辑:也{{ method_field('DELETE') }}从您的表单中删除,因为定义的路由方法是 post。