Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sunrise's avatar

How to add CsrfToken when using laravel and vue-resource?

How to add CsrfToken when using laravel and vue-resource?

<script>
    Vue.config.debug = true;
    var vm = new Vue({
        el: "#app",
        data: {
            items: [{
                id:1,
                message: 'Apple',
                num: 1,
                price: 5
            }, {
                id:2,
                message: 'Peach',
                num: 1,
                price: 10
            }, {
                id:3,
                message: 'Orange',
                num: 1,
                price: 15
            }, {
                id:4,
                message: 'Pear',
                num: 1,
                price: 20
            }]
        },
        methods: {
            fillIn: function (index, n) {
                var formData = new FormData();
                var itemId=this.items[index].id;

                this.items[index].num = n;

                formData.append('id', itemId);
                formData.append('num', n);

                this.$http.post('/someUrl', formData,{
                    before(request) {
                        if (this.previousRequest) {
                            this.previousRequest.abort();
                        }
                        this.previousRequest = request;
                    }
                }).then((response) => {
                    // success callback
                }, (response) => {
                    // error callback
                });
            }
        },
        computed: {
            nums: function() {
                return [1,2,3,4,5];
            },
            allSelected: {
                get: function() {
                    for (var i = 0, length = this.items.length; i < length; i++) {
                        if (this.items[i].selected === false) {
                            return false;
                        }
                    }
                    return true;
                },
                set: function(val) {
                    for (var i = 0, length = this.items.length; i < length; i++) {
                        this.items[i].selected = val;
                    }
                }
            },
            sum: function() {
                var totalAmount = 0;
                for (var i = 0, length = this.items.length; i < length; i++) {
                    var item = this.items[i];
                    if (item.selected === true) {
                        totalAmount += item.price * item.num;
                    }
                }
                return totalAmount;
            }
        }
    });

</script>

There is CsrfToken problem when using the code above,how to add it?

0 likes
7 replies
InaniELHoussain's avatar

in your metadata (meta name="csrf_token" content="{!! csrf_token() !!}"/)

PS : of course put them in < /> instead of ( /)

and add this in your Script TAG

$.ajaxSetup({
    headers: {
        'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content')
 }
});
nate.a.johnson's avatar

If you are using Vue, here's the way to go:

Vue.http.interceptors.push(function (request, next) {
    request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken;
    next();
});

You can get the token in other ways than the global Laravel object too. If you want to use that object though, you will need something like this in your head tag.

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>
2 likes
sunrise's avatar

@nate.a.johnson

Thanks!

I am using vue,I added my vuejs code .

Could you please show me where I should put the csrfToken code in my vuejs code?

ajax requst is in fillIn method.

nate.a.johnson's avatar

It can go anywhere. I put mine in my app.js file, which is the entry point for web pack to build my app. It's an interceptor, so as long as it is defined somewhere, it will always be called on every request to add that token.

1 like
it-systemmanagement's avatar

If i use that script tag in my header.

I get the error message:

[Vue warn]: Cannot find element: #app

bkuhl's avatar

Using Nate's approach in Vue 2.0, I get an error. However another google result led me to this solution:

Vue.http.headers.common['X-CSRF-TOKEN'] = document.head.querySelector('meta[name="csrf-token"]').content;
3 likes

Please or to participate in this conversation.