How to pass Laravel CSRF token value to Vue.js?

Sometimes, we want to pass Laravel CSRF token value to Vue.js.

In this article, we’ll look at how to pass Laravel CSRF token value to Vue.js.

How to pass Laravel CSRF token value to Vue.js?

To pass Laravel CSRF token value to Vue.js, we can create a slot in our Vue component to accept the CSRF token.

For instance, we write

@extends('layouts.app')

@section('content')
<my-vue-component>
  {{ csrf_field() }}
</my-vue-component>
@endsection

to wrap my-vue-component with the csrf_field() helper.

Then in MyVueComponent.vue, we write

<template>
  <form>
    <slot> </slot>
  </form>
</template>

to add a slot into our component.

And the CSRF token will be interpolated there since we have {{ csrf_field() }} inside the my-vue-component tags.

Conclusion

To pass Laravel CSRF token value to Vue.js, we can create a slot in our Vue component to accept the CSRF token.