Anthony Rappa

Stuff I learned along the way

Trigger DELETE requests with a link in Laravel 5

I learned quickly that using resources in Laravel was a pain due to the fact you had to messy up your code with forms every time you wanted to send a DELETE request to the server. But you don’t have to, with some quick jQuery you can have it do all of the work for you:

First start with a link to the route you are trying to hit with a DELETE request, and add a data attribute called method:

Next, in whatever pre-loaded javascript file you prefer, (I merge mine into a global file that is versioned and loaded on every page.) add this code:

What this does is anywhere it finds a link with a data-method=”delete” attribute, it will inject the Laravel equivalent form beneath it with the provided HTTP Request type. As well as for good measure when the link it clicked it will ask the user to confirm, if they do the form will be triggered and the DELETE request will be processed by the server.

Obviously this method can be used with any HTTP Request type if needed.

The above produces the following in the source of the page:

That’s it, now all of the dirty work is done for you. Hope this helps!

« »

© 2017 Anthony Rappa. Theme by Anders Norén.