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>
Came across this problem whilst building multiple forms in a vue v-for loop.
added to data;
Added hidden form element
Try this:
And in your markup just use
<input type="hidden" name="_token" :value="csrf" />
EDIT
Bit of a rabbit hole but, one great feature of Vue is that it can easily handle POST, PATCH, etc. requests using AJAX and the vue-resource extension. Instead of using a
<form>
here you can process this data using your Vue component. If you were to take this route, you can set default headers to send with each request no matter what method it is, so you can always send your CSRF token.As I already wrote here, I would simply suggest to put this in your PHP file:
This way you're able to easily import your csrfToken from the JS part (Vue in this case).
Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since
window
is a JS global variable.Source: I got the trick from this post.
if you look at the
/resources/assets/js/bootstrap.js
you will find these linesI believe you are using axios for your requests. this means you need to add
in your
<head>
tag.Laravel version 5 or later
First you need to store your CSRF token in a HTML meta tag in your header:
Then you can add it to your script:
And in the template:
I think you need to write it like this:
and not like this:
If that doesn't work, maybe try this: