1

i want to logout the user to NON inertia url. so i have to pass the csrf token to a form with post methd.


<!-- Authentication -->
<form
    method="POST"
    :action="route('logout')"
>
    <input type="hidden" name="_token" :value="$page.props.csrf_token">
    <jet-dropdown-link
        colors="text-red-700 focus:bg-gray-200 hover:bg-gray-200"
        as="button"
    >
        logout
    </jet-dropdown-link>
</form>

but it gives me a 419 page expired response.

when i console.log("this.$page.props.csrf_token") it shows undefined.

what should i do?

Mohammad Hossein
  • 404
  • 7
  • 21
  • For anyone with the same issue, read https://github.com/inertiajs/pingcrm/issues/32#issuecomment-517950878 as well. – VipinKundal Aug 01 '22 at 14:33

4 Answers4

2

it was my bad sorry. i should have read the documentation carefully.

so you can share the token with inertia middleware.

namespace App\Http\Middleware;

class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            'csrf' => csrf_token(),
        ]);
    }
}

and then in inertia compenents access it throught:

this.$page.props.csrf

source

Mohammad Hossein
  • 404
  • 7
  • 21
1

You need to add @csrf under your "<form" and add

<meta name="csrf-token" content="{{ csrf_token() }}">

in of your layout

Vins
  • 114
  • 1
  • 8
1

the simplest way is using csrf_field:

<form>
    {{ @csrf_field() }}
    <!-- other fields -->
</form>    
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
mohammad asghari
  • 1,817
  • 1
  • 16
  • 23
0

For anyone else who needs to find a way to pass the csrf token to inertia, one use case I have specifically is the need to have an export csv file button that sends an actual, non-AJAX HTTP request - so cant rely on axios' auto csrf feature - so I can return a file download.. what I did was in my controller where I populate $page.props, you can set an attribute to the value of the method 'csrf_token()'.. so -

Inertia::render( 'VueComponent', [ 'attribute_name' => csrf_token() ]);

Erik White
  • 1,016
  • 1
  • 11
  • 13