How to refer laravel csrf field inside a vue template
Asked Answered
B

4

17

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?

Barilla answered 5/8, 2017 at 14:38 Comment(1)
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.Soni
F
70

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>
Fillin answered 5/8, 2017 at 14:49 Comment(1)
I used document.head.querySelector('meta[name="csrf-token"]').content to get csrf data and work now! Thanks a lot.Saxecoburggotha
S
3

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

Usage: <form v-csrf-token>

Snocat answered 25/11, 2020 at 11:57 Comment(0)
H
2

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'
};
Harrier answered 5/3, 2018 at 16:54 Comment(1)
Axios already provides this by default. If you're using axios and add this snippet you'll actually be breaking your calls by duplicating the encrypted csrf token cookie.Uzziel
D
0

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.

Deyo answered 5/8, 2017 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.