Back

[Resource Controller] route("resource.destroy") calls "resource.show"


ShiFoo posted 3 years ago

Hi everyone,

i have a bit of a struggle with the resource controllers. As you can guess from the topic, the resource.destroy route always triggers the resource.show route.

My controller and the route is pretty basic, because i was about to test everything when i encountered this problem.

Controller http://laravel.io/bin/l6W

Route: http://laravel.io/bin/WYD

Now i have a link like this one: <a href="{{ route('accounts.destroy',array($accountID)) }}">Delete</a>

When i click it, i get "Show" displayed. The return value of 'resource.show'.

Now i was worried that my XAMPP wouldn't process http verbs like PUT and DELETE. But i opened a telnet connection and everything worked fine. So the problem must be the "route(...)" to generate the link. How do i do it correctly so my webserver gets the desired "DELETE" verb?

Thanks for any hint!

ShiFoo

pavoltanuska replied 3 years ago Solution

As current browsers do not implement DELETE verb Laravel simulates it via hidden fields. You have to do it with help of Form like this:

{{ Form::open(array('route' => array('accounts.destroy', $accountID), 'method' => 'delete')) }}
    <button type="submit" >Delete Account</button>
{{ Form::close() }}

More details explained here: http://stackoverflow.com/questions/19643483/crud-laravel-4-how-to-link-to-destroy

ShiFoo replied 3 years ago

Thanks for the quick help! Worked like a charm :)

ShiFoo replied 3 years ago

For those who don't want to use forms but javascript... Apparently, as i just found out, jQuery does the trick, too...

function checkDelete(id) {
if (confirm('Really delete?')) {
    $.ajax({
      type: "DELETE",
      url: '/<resource>/' + id,
      success: function(result) {
        // do something
      }
    });
  }
}
<a href="javascript:checkDelete(1);">...</a>

The advantage of this approach is that you can cancel it because of the confirmation box.

Cheers

barryvdh replied 3 years ago

You can also just the unobtrusive jquery adapter: https://github.com/rails/jquery-ujs That looks for data attributes, for methods (post/put/delete), confirm popups or send as ajax, without any additional javascript.

<a href="{{ route('accounts.destroy',array($accountID)) }}" data-method="delete" rel="nofollow" data-confirm="Are you sure you want to delete this?">Delete this entry</a>
Pedro Paulo Skakum replied 4 months ago

@barryvdh

You can also just the unobtrusive jquery adapter: https://github.com/rails/jquery-ujs That looks for data attributes, for methods (post/put/delete), confirm popups or send as ajax, without any additional javascript.

I come across:

TokenMismatchException

Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us