LoginSignup
9
8

More than 3 years have passed since last update.

Larave + Vue で普通にFormを使う際のCSRF Token処理

Posted at

Laravel 5.8
Vue 2.5.17

VueはSPAでやることが多いみたいですが、Ajaxではなく、単純にLaravelのControllerにPostをする場合の話

LaravelのBladeを利用する場合は以下をFormに埋め込めばいいですが、もちろんvueのコンポーネントで利用できないので手動で埋め込んでやる必要がある。

<form>
    @csrf
</form>

やり方はシンプル、blade上でcsrf tokenを取得して、コンポーネントに連携するだけ

//blade.php
<component :csrf="{{json_encode(csrf_token())}}"></component>
//Vue component

<template>
  <form>
    <input type="hidden" name="_token" v-bind:value="csrf">
  </form>
</template>

<script>
  export default {
    props:  {
      csrf: {
        type: String,
        required: true,
      }
    }
  }
</script>
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8