@consil Why do you want the delete links to be anchors and not forms? You really want to use forms for an action that modifies a resource, which DELETE does.
Asking a user to confirm a deletion is easy with a bit of JavaScript. You could add a simple data attribute to your form and then listen for clicks on that:
<form action="/your/item/url" method="POST" data-confirm="Are you sure you wish to delete this resource?">
<input type="hidden" name="_method" value="DELETE" />
<button type="submit">Delete</button>
</form>
$('[data-confirm]').on('click', function (e) {
if (! confirm($(this).data('confirm')) {
e.preventDefault();
e.stopImmediatePropagation();
}
});
If you want to use JavaScript, you can then intercept the form submission and do an AJAX request instead, and act based on the response status.
$('.some-selector').filter('form').on('submit', function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
beforeSend: function () {
// Do something before the AJAX request is sent
// Maybe show a loading indicator, disable the submit button, etc.
},
method: 'DELETE',
url: $form.attr('action')
})
.fail(function (jqXHR) {
// Deletion failed
// If you returned validation messages as a JSON response,
// you’ll find them in jqXHR.responseJSON
})
.done(function (response) {
// Do something with response
// i.e. remove row from table, display success message, etc
})
.always(function () {
// If you did something in beforeSend, un-do it here
// i.e. re-enable any buttons that were disabled
});
});
For CSRF, the Laravel docs has a section on how to handle this: https://laravel.com/docs/master/routing#csrf-x-csrf-token
So in some common bit of JavaScript that’s included before your form handlers, attach the CSRF token to AJAX requests:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});