wiwa1978
wiwa1978

Reputation: 2687

Laravel delete method not working with DELETE verb

In my routes file, I have

  Route::delete('events/{events}', ['as' => 'events_delete', 'uses' => 'Admin\EventsController@destroy'] );

In my view file I have

<a href="{!! route('events_delete', ['id' => $event->id ]) !!}" type="button" class="btn btn-sm btn-danger"><em class="fa fa-trash"></em></a>

This does not work. When I change the route to

  Route::get('events/{events}', ['as' => 'events_delete', 'uses' => 'Admin\EventsController@destroy'] );

it does work. However I don't like the idea of using a GET verb to delete items instead of the DELETE verb. It feels like a trick...

How can I change the form code to make sure it sends a DELETE verb?

Solution 1 (from TheFallen): with DELETE VERB in routes file

<form action="{!! route('events_delete', ['id' => $event->id ]) !!}" method="POST">
   {{ method_field('DELETE') }}
   {{ csrf_field() }}
   <button class="btn btn-danger btn-sm" type="submit"><em class="fa fa-trash"></em></button>
</form>

Solution 2: with GET VERB in routes file

<a href="{!! route('events_delete', ['id' => $event->id ]) !!}" type="button" class="btn btn-sm btn-danger"><em class="fa fa-trash"></em></a>

Upvotes: 1

Views: 1229

Answers (2)

thefallen
thefallen

Reputation: 9749

You have to make a delete request to use the route this way, which you can do with a form, otherwise with the anchor you're making a get request.

If you already don't have the laravelcollective/html package install it from composer to use the forms facade. Then you can make the request like this:

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

EDIT:

Without the forms facade:

<form action="{{ $yourRoute }}" method="POST">
    {{ method_field('DELETE') }}
    {{ csrf_field() }}
    <button class="btn btn-danger btn-sm" type="submit"><em class="fa fa-trash"></em></button>
</form>

Upvotes: 3

Arunkumar Kubendran
Arunkumar Kubendran

Reputation: 27

That will produce a GET request, therefore it will not match Route::delete

HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form.

Refer: https://laravel.com/docs/master/routing#form-method-spoofing

To call the delete route, you have to implement using jquery

<a eventid="{{$event->id}}" href="#" type="button" class="btn btn-sm btn-danger"><em class="fa fa-trash"></em></a>

$(document).on("click",".anchorclass",function(e){
e.preventDefault();
if(!confirm("Are you sure?")) return;

 $.ajax({
            type: "DELETE",
            url: 'events/'+$(this).attr("eventid"),
            success: function(data) {
                //Process results
            }
        });

}); 

Upvotes: 1

Related Questions