Search code examples
laravel-5.3vuejs2csrf

Vue 2 Laravel 5.3 POST method submit with token mismatch


Not sure how to set up csrf_token properly. here is my codes related

Item-card.vue

<template>
.....
.....
    <input v-if="selected == 'name' + product.id" v-model="name" type="text" class="form-control" aria-describedby="basic-addon1" @blur.prevent="updateName">
    <form id="update-product-name" :action="'http://localhost:8000/updateProductName/'+product.id" method="POST" style="display: none;">
.....
.....
</template>
<script>
.....
.....
   methods:{
      updateName(){
        document.getElementById('update-product-name').submit();
      }
   }
.....
.....
</script>

app.blade.php

<head>
.....

    <!-- CSRF Token -->
    <meta id="token" name="csrf-token" content="{{ csrf_token() }}">
.....
</head>

app.js

Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("value");

Reloaded page and it shows:

TokenMismatchException in VerifyCsrfToken.php line 68:

I did some research and found that I dont have to add csrf_token in every single form I submit and just need to put it in the head meta tag. However it does not seem to work. How should it be set up?

EDIT#1

I did a bit of research and changed attr("value") into attr("content") but the same issue happens to me.


Solution

  • As I mentioned in the comments the reason you were getting a TokenMismatchException was because the csrf header was not being sent.

    Vue.http.headers.common['X-CSRF-TOKEN'] = $("#token").attr("content");

    The above will allow you to include the csrf header when using Vue-Resource.

    You will need to change the behaviour of your form so that it gets submitted with vue/vue-resource instead of the default browser submission.

    One way to do this would be:

    updateName() {
    
        let data = {
            //Add the data you want to be sent in the request here e.g.
            //name: this.name
        }
    
        this.$http.post('/updateProductName/' + this.product.id, data)
            .then(r => {
                //Do something on success
            })
            .catch(r => console.log(r))
    }
    

    Hope this helps!