The issue you're experiencing is related to the CSRF token not being updated when using the Inertia.js form submission, which leads to a 419 error on subsequent requests. This happens because the CSRF token is regenerated on session regeneration, but the Inertia.js form does not automatically update the CSRF token in the meta tag.
Here's a solution to ensure the CSRF token is updated correctly:
-
Update the CSRF Token in the Inertia Response:
When you regenerate the session in your
storemethod, you need to ensure that the new CSRF token is sent back to the client. You can do this by including the CSRF token in the Inertia response.Modify your
storemethod to include the CSRF token in the response:public function store(LoginRequest $request): RedirectResponse { $request->authenticate(); $request->session()->regenerate(); return redirect()->intended(route('home', absolute: false)) ->with(['csrf_token' => csrf_token()]); } -
Update the CSRF Token on the Client Side:
On the client side, you need to listen for the Inertia response and update the CSRF token in the meta tag. You can do this by using an Inertia event listener.
In your main JavaScript file where you initialize Inertia, add an event listener for the
successevent:import { Inertia } from '@inertiajs/inertia'; Inertia.on('success', (event) => { if (event.detail.page.props.csrf_token) { const newToken = event.detail.page.props.csrf_token; document.querySelector('meta[name="csrf-token"]').setAttribute('content', newToken); window.axios.defaults.headers.common['X-CSRF-TOKEN'] = newToken; } }); -
Ensure Axios Uses the Updated CSRF Token:
Make sure that Axios is configured to use the CSRF token from the meta tag. This is typically done in your main JavaScript file:
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
By following these steps, you ensure that the CSRF token is updated both in the meta tag and in Axios headers whenever the session is regenerated, preventing the 419 error on subsequent requests.