-1

I'm creating a application with Svelte.js and Larvel 6 as backend (wewowweb/laravel-svelte-preset). How can i get the csrf-token for a form? The expression @csrf is displayed as plain text.

Peter Wyss
  • 19
  • 1
  • 3
  • I'm not sure how to answer your question (no familiarity with svelte), but just a heads up, `@csrf` wont't work in a `.js` file; it's a Laravel helper and is only available in a `.php` file. – Tim Lewis Nov 26 '19 at 19:16
  • Maybe a http request is the only way? – Peter Wyss Nov 26 '19 at 19:39
  • Can't say for sure. If you're loading `svelte.js` in a `.blade.php` file, then you can define `let _TOKEN = "{{ csrf_token() }}"`, before you include `svelte.js` and you can use `_TOKEN` in subsequent requests. Or, you can disable `csrf` if you want (wouldn't recommend, but possible) – Tim Lewis Nov 26 '19 at 19:42
  • 1
    That works. Thank you very much! – Peter Wyss Nov 26 '19 at 21:47

1 Answers1

1

To update this question: Using Laravel 8 and Svelte, I simply stripped out all the code save the form and @crf from the resources/views/auth/register.blade.php file like so (ignore the Tailwindcss):

@extends('layouts.app')
@section('content')
<form data-register method="POST" action="{{ route('register') }}"
 class="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
  @csrf
  <script src="{{ asset('js/register.js') }}"></script>
</form>
@endsection

If you want your form totally in Svelte, so you can execute it all asyncronously or have it tied to other components, you could just call the @csrf by itself, no form. You would then have to put some code into your .svelte/.js file to move the input PHP creates pre-load into the form that SVELTE creates post-load and you're done! Maybe something like (untested, just guessed at and assuming a data-register attribute on the form)

import { onMount } from "svelte"

onMount(() => {
  let token = document.getElementsByName('_token')
  let form = document.querySelector('[data-register] form')
  if(token && form){
    form.appendChild(token[0])
  }
}

I've tested the PHP way, works like a CHARM. The JS way kept throwing a 419 error, so I basically just went with option 1.