laravel 使用表单软删除

laravel soft delete using a form

您好,我正在尝试使用表单软删除和恢复用户,我使用了几个用于用户身份验证和角色的包 Zizaco Confide and Zizaco Entrust。我已将以下内容添加到 user.php 模型

use SoftDeletingTrait;
use ConfideUser;
use HasRole;
protected $softDelete = true;

我已经 运行 进行了测试以测试它是否有效:

Route::get('/deleteme', function(){ 
    User::find(2)->delete();
    return 'done';
});

这更新了时间戳字段,但是我想将其放入我的控制器中以整理内容并为其提供表单。所以我在 table 的用户中完成了此操作:

 @if(empty($user->deleted_at))
           {{Form::open(['method'=>'PATCH','action'=>
            ['UsersController@softDeleteUser',$user->id]])}}
              <button type="submit">Suspend</button>
              {{Form::close()}}  
            @else 
             {{Form::open(['method'=>'delete','action'=>
            ['UsersController@restoreUser',$user->id]])}}
                <button type="submit">Re-activate</button>
            {{Form::close()}}  
            @endif

在我的控制器中:

public function softDeleteUser($id){
    $user = User::find($id);
    $user->delete();
    // redirect
    return Redirect::to('/admin');
}

public function restoreUser($id) {
    User::find($id)->restore();        
    $user->save();
    Redirect::to("/admin");
}

在我的路线中:

Route::post('/admin/user/{resource}/delete', 
       array('as' => 'admin.user.delete', 'uses' 
       =>'UsersController@softDeleteUser'));
Route::post('/admin/user/{resource}/restore', 
      array('as' => 'admin.user.restore', 
     'uses' =>'UsersController@restoreUser'));

但是我得到这个错误:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException 

知道我做错了什么吗??

您已经将两个表单设置为使用 PATCH 和 DELETE 方法,但是您的路由设置为 POST (Route::post)。

您可以更改路线:

Route::patch('/admin/user/{resource}/delete', 
    array('as' => 'admin.user.delete', 'uses' 
    =>'UsersController@softDeleteUser'));
Route::delete('/admin/user/{resource}/restore', 
    array('as' => 'admin.user.restore', 
   'uses' =>'UsersController@restoreUser'));

或删除表单中的 method(它将默认为 POST)

{{Form::open(['action'=> ['UsersController@softDeleteUser',$user->id]])}}
     <button type="submit">Suspend</button>
{{Form::close()}}

{{Form::open(['action'=> ['UsersController@restoreUser',$user->id]])}}
     <button type="submit">Re-activate</button>
{{Form::close()}}