简体   繁体   中英

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. 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). I have tried both "delete" and "destroy" on my destroy($id) function, but each throws the same error. Do I need to put something on the model or routes.php to allow deletions?

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.

Since you use resourceful routing the destroy action is attached to the HTTP DELETE method. To clarify this, execute this command:

php artisan routes 

This command show you a detailed list of your routes asociations and HTTP methods.

To solve the problem try this:

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

I Hope works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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