Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created November 15, 2018 14:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save calebporzio/ae2d46ce2f270d2764a79fa4822a2c80 to your computer and use it in GitHub Desktop.
Save calebporzio/ae2d46ce2f270d2764a79fa4822a2c80 to your computer and use it in GitHub Desktop.
A Vue component to include Laravel's CSRF Token within form tag
// Usage:
// <vue-form method="PUT">
// <input type="text" name="email">
// <input type="submit">
// </vue-form>
<template>
<form :method="method.toUpperCase() == 'GET' ? 'GET' : 'POST'">
<input-hidden :value="csrfToken" name="_token"/>
<input-hidden
v-if="['GET', 'POST'].indexOf(method.toUpperCase()) === -1"
:value="method"
name="_method"
/>
<!--
This hidden submit button accomplishes 2 things:
1: Allows the user to hit "enter" while an input field is focused to submit the form.
2: Allows a mobile user to hit "Go" in the on-screen keyboard to submit the form.
-->
<input type="submit" class="absolute invisible z-0">
<slot/>
</form>
</template>
<script>
export default {
props: { method: { default: 'POST' }},
data() { return { csrfToken: null }},
created() {
this.csrfToken = document.querySelector('meta[name="csrf-token"]').content
},
}
</script>
@bradley-varol
Copy link

You should use mounted() and not created() to ensure the DOM is available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment