Laravel CSRF Field in Vue Component

Viewed 6098

I would like to ask how can I add the csrf_field() in my vue component. The error is

Property or method "csrfToken" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Here's the code:

<script>
export default {
  name: 'create',
  data: function(){
    return {
        msg: ''
    }
  },
  props:['test']
}
</script>
<template>
  <div id="app">
    <form action="#" method="POST">
      {{csrfToken()}}
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" class="form-control"> 
      </div>
      <div class="form-group">
        <label for="location">Location</label>
        <input type="text" id="location" class="form-control"> 
      </div>
      <div class="form-group">
        <label for="age">Age</label>
        <input type="number" id="age" class="form-control"> 
      </div>
      <div class="form-group">
        <input type="submit" class="btn btn-default"> 
      </div>
    </form>
  </div>
</template>

6 Answers

Laravel version 5 or later

First you need to store your CSRF token in a HTML meta tag in your header:

<meta name="csrf-token" content="{{ csrf_token() }}">

Then you can add it to your script:

<script>
export default {
  name: 'create',
  data: function(){
    return {
        msg: '',
        csrf: document.head.querySelector('meta[name="csrf-token"]').content
    }
  },
  props:['test']
}
</script>

And in the template:

<template>
  <div id="app">
    <form action="#" method="POST">
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" class="form-control"> 
      </div>
      <div class="form-group">
        <label for="location">Location</label>
        <input type="text" id="location" class="form-control"> 
      </div>
      <div class="form-group">
        <label for="age">Age</label>
        <input type="number" id="age" class="form-control"> 
      </div>
      <div class="form-group">
        <input type="submit" class="btn btn-default"> 
      </div>
      <input type="hidden" name="_token" :value="csrf">
    </form>
  </div>
</template>

Came across this problem whilst building multiple forms in a vue v-for loop.

added to data;

csrf: document.head.querySelector('meta[name="csrf-token"]').content,

Added hidden form element

<input type="hidden" name="_token" :value="csrf" /> 
Related