13
votes

I have a vue template that contains a form:

<form id="logout-form" :action="href" method="POST" style="display: none;">
        {{ csrf_field() }}
</form>

In laravel, forms must have a csrf_field() defined. But within a vue component, the statement {{ csrf_field() }} means that I have a method named csrf_field in my vue instance and I am calling it.

How do I add csrf_field under this circumstance?

4
You can send CSRF token as header headers['X-CSRF-TOKEN'].And also store it into into the meta tag of your app, and later on just get it for instance with document.querySelector.Belmin Bedak

4 Answers

56
votes

If you have the token in the meta tag of your header (view)

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

you could access the token using

data() {
    return {
        csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
    }
}

And add a hidden input field within the form and bind the csrf property to the value like this:

<form id="logout-form" :action="href" method="POST" style="display: none;">
    <input type="hidden" name="_token" :value="csrf">
</form>
2
votes

If you're using axios with Vue2 for your ajax requests you can just add the following (usually in your bootstrap.js file):

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    'X-Requested-With': 'XMLHttpRequest'
};
1
votes

You can use this package: npm install vue-laravel-csrf

Usage: <form v-csrf-token>

0
votes

This is how i use it:

{!! csrf_field() !!}

Put that in your form.

and in your vue script you can simply

methods: {
                submitForm: function(e) {

                  var form = e.target || e.srcElement;
                  var action = form.action;

get the form and his action then the data value will be:

data: $(form).serialize()

This works perfectly for me and gives no errors at all.