2
               

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:                                        

  •           
       

2 Answers         

8
                   

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

       
0
                   

Methods to remove/restore records from the table. Laravel 5.x, 6.x, 7.x

To enable soft deletes for a model, use the Illuminate\Database\Eloquent\SoftDeletes trait on the model:
 <?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();
        //恢复多个模型
     $flight = App\Flight::withTrashed() ->where('airline_id', 1) ->restore();
    // 强制删除单个模型实例...
   $flight->forceDelete();
  // 强制删除所有相关模型...
  $flight->history()->forceDelete();             

       

来自  https://stackoverflow.com/questions/44075173/how-to-force-delete-in-laravel-5-4