Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer laravel csrf field inside a vue template

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?

like image 374
Tanmay Avatar asked Aug 05 '17 14:08

Tanmay


2 Answers

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>
like image 55
linktoahref Avatar answered Sep 20 '22 11:09

linktoahref


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'
};
like image 39
omarjebari Avatar answered Sep 20 '22 11:09

omarjebari