Skip to content

Instantly share code, notes, and snippets.

@guilhermemuller
Created November 27, 2021 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guilhermemuller/114064dfe4e8ee49c37cce6f1a824081 to your computer and use it in GitHub Desktop.
Save guilhermemuller/114064dfe4e8ee49c37cce6f1a824081 to your computer and use it in GitHub Desktop.
Laravel dynamic delete form creation
// This is a simple update of https://gist.github.com/JeffreyWay/5112282
/*
<a href="posts/2" data-method="delete"> <---- We want to send an HTTP DELETE request
- Or, request confirmation in the process -
<a href="posts/2" data-method="delete" data-confirm="Are you sure?">
*/
window.addEventListener('DOMContentLoaded', (event) => {
(function() {
var laravel = {
initialize: function() {
this.methodLinks = document.querySelectorAll('a[data-method]');
this.registerEvents();
},
registerEvents: function() {
this.methodLinks.forEach(item => {
item.addEventListener('click', event => {
event.preventDefault();
this.handleMethod(item);
return false;
})
});
},
handleMethod: function(item) {
let link = item;
let httpMethod = link.dataset.method.toUpperCase();
let form;
let confirm = link.dataset.confirm || "Are you sure you want to delete this entry?";
// If the data-method attribute is not PUT or DELETE,
// then we don't know what to do. Just ignore.
if ( ! ['PUT', 'DELETE'].includes(httpMethod) ) {
return;
}
// Allow user to optionally provide data-confirm="Are you sure?"
if ( confirm ) {
if ( ! laravel.verifyConfirm(confirm) ) {
return false;
}
}
form = laravel.createForm(link);
form.submit();
},
verifyConfirm: function(confirmPrompt) {
return confirm(confirmPrompt);
},
createForm: function(link) {
let form = document.createElement('form');
form.setAttribute('method', 'POST');
form.setAttribute('action', link.getAttribute('href'));
let tokenInput = document.createElement('input');
tokenInput.setAttribute('type', 'hidden');
tokenInput.setAttribute('name', '_token');
tokenInput.setAttribute('value', '<?php echo csrf_token(); ?>'); // needs to be improved
form.append(tokenInput);
let methodInput = document.createElement('input');
methodInput.setAttribute('type', 'hidden');
methodInput.setAttribute('name', '_method');
methodInput.setAttribute('value', link.dataset.method);
form.append(methodInput);
document.body.append(form);
return form;
}
};
laravel.initialize();
})();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment