Created
November 27, 2021 10:35
-
-
Save guilhermemuller/114064dfe4e8ee49c37cce6f1a824081 to your computer and use it in GitHub Desktop.
Laravel dynamic delete form creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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