简体   繁体   English

如何使用资源丰富的路由删除Laravel 4.2中的单个记录?

[英]How to delete individual records in Laravel 4.2 using resourceful routing?

I'm building a "cookbook" app in Laravel 4.2 with resourceful routing set up for recipes and categories. 我正在Laravel 4.2中构建一个“食谱”应用程序,并为食谱和类别设置了资源丰富的路由。 On the categories/{$id}/edit page (edit.blade.php), I have a model-bound form to edit the category, and underneath that, I have an additional form posting to the CategoryController@destroy method to delete, but every time I try, it throws a MethodNotAllowedHttpException (which is a protected method). 在category / {$ id} / edit页面(edit.blade.php)上,我有一个绑定模型的表单来编辑类别,在其下,我还有一个附加的表单发布到CategoryController@destroy方法中,以进行删除,但是每次尝试时,它都会抛出MethodNotAllowedHttpException (这是一个受保护的方法)。 I have tried both "delete" and "destroy" on my destroy($id) function, but each throws the same error. 我在我的destroy($ id)函数上尝试了“删除”和“销毁”,但是每个都抛出相同的错误。 Do I need to put something on the model or routes.php to allow deletions? 我是否需要在模型或route.php上放一些东西以允许删除?

Method being called: 方法被调用:

public function destroy($id)
{
    $category = Category::find($id);
    $category->destroy();

    return Redirect::to('/categories');
}

And form which is calling it: 以及形式如下:

{{ Form::open(array('action' => array('CategoryController@destroy', $category->id))) }}

{{ Form::submit('Delete Category', ['class' => 'red_button']) }}

{{ Form::close() }}

Category model (which has no reference to deletions, but I'm adding it just in case): 类别模型 (它没有删除内容的引用,但为防万一,我添加了它):

class Category extends \Eloquent {
    /*Whitelist what user can enter into form and submit*/
    protected $fillable = [
'name', 'description', 'thumbnail'
    ];

    /*Set up One To Many relationship for users to recipes*/
    public function recipes()
    {
        return $this -> hasMany('Recipe');
    }
}

Thanks for any help! 谢谢你的帮助!

By default when you open a form whith Form::open the method used is "POST", you need to set this method to DELETE instead. 默认情况下,当您通过Form :: open打开一个窗体时,使用的方法是“ POST”,您需要将此方法设置为DELETE。

Since you use resourceful routing the destroy action is attached to the HTTP DELETE method. 由于您使用的是资源丰富的路由,所以将destroy操作附加到HTTP DELETE方法。 To clarify this, execute this command: 为了澄清这一点,执行以下命令:

php artisan routes 

This command show you a detailed list of your routes asociations and HTTP methods. 此命令向您显示路由关联和HTTP方法的详细列表。

To solve the problem try this: 要解决此问题,请尝试以下操作:

 {{ Form::open(array(
     'action' => array('CategoryController@destroy', $category->id),
     'method' => 'delete')) }} 

I Hope works for you. 我希望为您工作。

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

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