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

gmanish's avatar

Passing on CSRF token to vue components through props

I want to pass the CSRF token from my blade file (where my vue components are declared) to the component like so:

file: petty-cash.blade.php

<petty-cash v-bind:api="api" v-bind:csrf_token="{{ csrf_token() }}">
</petty-cash>

This doesn't work, neither does it give any error. The prop csrf_token remains uninitialized.

What am I missing here?

0 likes
3 replies
bobbybouwmann's avatar

Did you add the property to your Vue component as well? It might also have to do with how you call the token. I believe you need {!! csrf_token() !!} instead.

It's also highly recommended to do this kind of stuff on a global base. So instead of passing it to a component so pass the variable of the csrf token to a global variable which you can use in all your other components

You have multiple options here, but it's recommended to do it in the head of your html

// app.blade.php
<!doctype html>
<html>
<head>

    <meta name="_token" content="{!! csrf_token() !!}"/>

</head>
<body>

// Include your vuejs script here

</body>
</html>

When you do an ajax request for example you can fetch the token from the head of the document. Here is an example with jQuery, but you can do it with any kind of JS

// app.js

$.ajax({
    url: http://someurl.com/update,
    type: 'POST',
    headers: {
        'X-CSRF-Token': $('meta[name=_token]').attr('content')
    },
    data: {
        'username': 'new_username'
    }
}).done(function () {
    alert('done');
});
gmanish's avatar

Yes, I've added the prop to my vue component, like so:

File PettyCash.vue:

export default {

      props: [
          'api',
          'csrf_token'
      ],
 ...
}

I tried using the {!! csrf_token() !!} construct also, no difference. Actually, I probably missed it earlier, but vue is spitting out a warning:

[Vue warn]: Property or method "xPxRC236KN9Hd60vPAGRCTSsrnXkczUQ4IO2F8EL" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Thanks for the header suggestion, I'll go with it if I cannot get this to work.

bobbybouwmann's avatar

Mmh it looks fine to me. The header suggestion is a more recommended way, but code wise your code should work just fine!

Please or to participate in this conversation.