How to pass laravel CSRF token value to vue
A better way is simply to pass the csrf token via a slot into the vue component.
In blade.php file:
@extends('layouts.app')
@section('content')
<my-vue-component>
{{ csrf_field() }}
</my-vue-component>
@endsection
In MyVueComponent.vue
<form role="form">
<slot>
<!-- CSRF gets injected into this slot -->
</slot>
<!-- form fields here -->
</form>
Very Easy Solution
Just add a hidden field inside the form. An Example
<form id="logout-form" action="/logout" method="POST" style="display: none;">
<input type="hidden" name="_token" :value="csrf">
</form>
Now add csrf
variable inside script at the vue file, like this. (Remember, it must be inside data).
<script>
export default {
data: () => ({
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
}),
}
</script>
N.B. You will see a meta tag in your blade.php
file like this.
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
If there is nothing like this, you need to place it there.
My solution to this is that all vue components get csrf token right before a request is made. I put this in my bootstrap.js file.
Vue.http.interceptors.push((request, next) => {
request.headers.set('X-CSRF-TOKEN', CoolApp.csrfToken);
next();
});
Then have a class CoolApp.php
public function getScriptVariables()
{
return json_encode([
'csrfToken' => csrf_token(),
]);
}
I solved it thanks to these two answers:
1) First I read this one, which led me to
2) This second one.
So, in my form I keep this:
{{ csrf_field() }}
And inside the js file I only add the following (outside and above the Vue instance):
var csrf_token = $('meta[name="csrf-token"]').attr('content');
So the whole js code is:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
/*Event handling within vue*/
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
token : csrf_token,
},
methods : {
postStatus : function (e) {
e.preventDefault();
console.log('Posted: '+this.post+ '. Token: '+this.token);
$.ajax({
url : '/posts',
type : 'post',
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
});
}
},
});