使用表单进行laravel软删除

时间:2015-02-07 21:58:04

标签: laravel eloquent soft-delete

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

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

我正在进行测试,以便对此进行测试:

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

并且这更新了时间戳字段,但是我想把它放到我的控制器中来整理并给它一个表单。所以我在用户表中做到了这一点:

 @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 

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:1)

您已将两个表单设置为使用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()}}