简体   繁体   English

如何在 Laravel 5.4 中强制删除

[英]how to force delete in laravel 5.4

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?为什么它不起作用,我该如何解决?

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。

Methods to remove/restore records from the table.从表中删除/恢复记录的方法。 Laravel 5.x, 6.x, 7.x Laravel 5.x、6.x、7.x

To enable soft deletes for a model, use the Illuminate\\Database\\Eloquent\\SoftDeletes trait on the model:要为模型启用软删除,请在模型上使用Illuminate\\Database\\Eloquent\\SoftDeletes特征

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

Soft delete: This will move record to trash软删除:这会将记录移至垃圾箱

$user= User::Find($id);
$user->delete();

Force Delete: Permanently Deleting Models强制删除:永久删除模型

$user= User::withTrashed()->Find($id);
$user->forceDelete();

Restore: Restoring Soft Deleted Models恢复:恢复软删除的模型

$user= User::withTrashed()->Find($id);
$user->restore();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM