Csrf token exist by default on either the bootstrap.js or app.js file. You dont have to explicitly add it on any vue component.
Sep 30, 2020
5
Level 4
Laravel CSRF Token in Vue
I haven't found a standard/definitive solution for handling the Laravel CSRF token in Vue components and wanted to see what other solutions people have come up with.
My best solution so far is to create a global component and then wherever I need the CSRF token I add <csrf-token-input />
<!-- components\CSRFTokenInput.vue -->
<template>
<input type="hidden" name="_token" :value="csrf">
</template>
<script>
/**
* Laravel CSRF Token hidden input.
*
* The following is required in the header of the blade file responsible for containing the HTML header info:
* <meta name="csrf-token" content="{{ csrf_token() }}">
*/
export default {
created() {
if (! this.csrf) {
console.warn('The CSRF token is missing. Ensure that the HTML header includes the following: <meta name="csrf-token" content="{{ csrf_token() }}">');
}
},
data() {
return {
csrf: document.head.querySelector('meta[name="csrf-token"]') ? document.head.querySelector('meta[name="csrf-token"]').content : '',
}
},
}
</script>
Does anyone have any solutions that may be better? If not, do you have any suggestions to improve this solution?
Thanks!
Please or to participate in this conversation.