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:
1 |
<a href="{{ route('users.destroy', $user->id) }}" data-method="delete" name="delete_item">Delete</a> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$('[data-method]').append(function(){ return "\n"+ "<form action='"+$(this).attr('href')+"' method='POST' name='delete_item' style='display:none'>\n"+ " <input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n"+ " <input type='hidden' name='_token' value='"+$('meta[name="_token"]').attr('content')+"'>\n"+ "</form>\n" }) .removeAttr('href') .attr('style','cursor:pointer;') .attr('onclick','$(this).find("form").submit();'); /* Generic are you sure dialog */ $('form[name=delete_item]').submit(function(){ return confirm("Are you sure you want to delete this item?"); }); |
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:
1 2 3 4 5 6 |
<a data-method="delete" style="cursor:pointer;" onclick="$(this).find('form').submit();">Delete <form action="http://localhost/users/1" method="POST" name="delete_item" style="display:none"> <input type="hidden" name="_method" value="delete"> <input type="hidden" name="_token" value="vk5BscHjhgKcBjQSUGeWIqc949DJQ5EuXVmE1hwX"> </form> </a> |
That’s it, now all of the dirty work is done for you. Hope this helps!
Aleh
September 16, 2016 — 7:08 am
Fixed.
Thank you!
Everything is working.
Aleh
September 15, 2016 — 8:10 am
not work in laravel 5.3…
MethodNotAllowedHttpException in RouteCollection.php line 218:
in RouteCollection.php line 218
at RouteCollection->methodNotAllowed(array(‘POST’)) in RouteCollection.php line 205
at RouteCollection->getRouteForMethods(object(Request), array(‘POST’)) in RouteCollection.php line 158