Ask Your Question
3

What is the method of adding a global CSRF token on Laravel Inertia?

asked 2022-10-09 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-11-10 03:00:00 +0000

lakamha gravatar image

The method of adding a global CSRF token on Laravel Inertia is as follows:

  1. Add the following code to your app/Http/Middleware/VerifyCsrfToken.php file:
use Illuminate\Http\Request;

protected function addCookieToResponse($request, $response)
{
    $response->headers->set('X-CSRF-TOKEN', $request->session()->token());

    return parent::addCookieToResponse($request, $response);
}
  1. In your Vue file, include @inertia and define a meta tag for the CSRF token:
<template>
  <div>
    <!-- Your component here -->
  </div>
</template>

<script>
export default {
  metaInfo() {
    return {
      title: 'Your Page Title',
      meta: [
        {
          name: 'csrf-token',
          content: this.$page.props.csrfToken,
        },
      ],
    };
  },
};
</script>

<style>
  /*Your component's styles here*/
</style>

@inertia
  1. In your layout file, define a meta tag for the CSRF token:
<!doctype html>
<html>
<head>
    <!-- Other head tags here -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
    @inertia
</body>
</html>

With these steps, you have now added a global CSRF token which will be available for all your pages.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-09 11:00:00 +0000

Seen: 11 times

Last updated: Nov 10 '22