delete in laravel with get using Route::resource()

2019-09-08 15:11发布

问题:

I'm trying to delete in laravel using GET instead of DELETE because my shared server doesn't support DELETE verb.

So, I used Jeffrey Way's method

Thing is in my routes.php, I use

 Route::resource('users', 'UserController');

For example.

So, When I use GET instead of DELETE with resource, system think I will use show method, instead of destroy method.

The only way I see to do that is not using resource method to route, and detail all my routes, but I don't like it, it is kind of heavy to read.

Is it any way to keep using resource() and have a customized route to destroy?

Tx!

回答1:

HTML forms don't actually support PUT, PATCH, or DELETE actions; they only support GET or POST requests.

Instead, Laravel spoofs the method to allow you to use these using a hidden _method field, which you can read up on in the docs.

Using Route::resource will automatically route DELETE methods to your destroy function in the controller.

If you are using Form helpers, then you can use the following in your Form::open() to specify the delete method:

{!! Form::open(['method' => 'DELETE']) !!}

If you aren't then you can simply include it like so {{ method_field('DELETE') }} inside your HTML form.

If you don't spoof it and use a GET request then the Route::resource will associate this with the show function in your controller.

Using a button to do this

{!! Form::open(['method' => 'DELETE']) !!}
{!! Form::submit('Delete') !!}
{!! Form::close() !!}


回答2:

One option is to use Route::resource with except parameter and customize excepted routes as desired.

Example:

Route::resource('product, 'ProductController', ['except' => ['destroy']]); Route::get('product/{id}/destroy','ProductController@destroy');

Haven't found better solution yet.