1

I'm trying to build and application on Laravel, VueJS and inertiajs.

I'm using maatwebsite/excel to export my data into excel format.

I've a vue component which has a normal HTML form

home.vue

<form action="/project-profile" target="_blank" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="_token" :value="csrf.content" />
    <input type="hidden" name="slug" :value="JSON.stringify(generalDetails.slug)" />
    <button class="font-medium tracking-wide">Download Profile</button>
</form>

And on mounted method I'm just placing my csrf token.

mounted() {
    this.csrf = document.head.querySelector('meta[name="csrf-token"]');
}

In Laravel part I made a route in web.php file

Route::post('project-profile','ProjectProfileExportController@ProjectProfile');

Whenever I try to export or submit the form, I get page expired error, I followed few guide and it says there is issue with csrf_token but while inspecting the form I can see token is placed appropriately.

I tried doing the same by making this as api, api.php:

Route::post('project-profile', 'ProjectProfileExportController@ProjectProfile');

But this thing also not work as expected.

Screenshot of page expired screen

Screenshot of inspect form element

Any better approach is welcome. Thanks.

1 Answer 1

9

Creator of Inertia.js here.

So, we recommend not manually sending the csrf token on each request like this.

A better approach is to use the CSRF functionality already built into axios for this. Axios is the HTTP library that Inertia uses under the hood.

Axios automatically checks for the existence of an XSRF-TOKEN cookie. If it's present, it will then include the token in an X-XSRF-TOKEN header for any requests it makes.

The easiest way to implement this is using server-side middleware. Simply include the XSRF-TOKEN cookie on each response, and then verify the token using the X-XSRF-TOKEN header sent in the requests from axios.

Some frameworks, such as Laravel, do this automatically, meaning there is no configuration required. So, I'd recommend removing the csrf-token meta tag from your template, and removing the _token from your requests. That should take care of your issues.

That all said, keep in mind that you will not be able to download an Excel file from an Inertia request. All Inertia requests MUST return a valid Inertia response. You can use window.open for this. Something like this:

window.open(`/url/to/excel/download?slug=${generalDetails.}`, '_blank')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.