Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Michael__'s avatar

[L5] Regenerate CSRF Token each request

Hey,

how can I make Laravel regenerate the token for each request, instead only for a new session?

Thanks

0 likes
8 replies
khakhana's avatar

You can override method addCookieToResponse() in App\Http\Middleware\VerifyCsrfToken for this.

    protected function addCookieToResponse($request, $response)
    {
        $request->session()->regenerateToken();
        return parent::addCookieToResponse($request, $response);
    }
Michael__'s avatar

@khakhana I tried using the following:


class VerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken { protected function addCookieToResponse($request, $response) { $request->session()->regenerateToken(); return parent::addCookieToResponse($request, $response); } }

But that leads to a RuntimeException in Request.php line 649: Session store not set on request. when submitting a POSt request.

Edit: What are the correct code tags for the forums?

Thanks

khakhana's avatar

In Exception i think in Kernel.php you have ** VerifyCsrfToken** before StartSession

I think my code is't not work for you. because in this case, application regenerate token before assign to cookies, but if you use csrf_token() it use token before regenerated.

If you want to use this. you must add token to "_token" by js.

Ps. for your question, pls follow link https://help.github.com/articles/github-flavored-markdown/#fenced-code-blocks

Michael__'s avatar

Okay, I have it now after StartSession but now I get a TokenMismatchException whenever I make a post request :(

Does it not generate a new token when I perform a POST request as well, before validating the submitted one (and therefore make it invalid)?

Thanks for your help!

khakhana's avatar
Level 1

You get TokenMismatchException because application call csrf_token() before $session->regenerateToken();, It use old token match with new token always.

If you want to use csrf_token(), you would to find somewhere to add $session()->regenerateToken(); or Session::regenerateToken();

PS. in my case it work because i use with AngularJS and get token from cookies.

Michael__'s avatar

Many thanks, I added it to my main controller!

srikant's avatar

where did you put this? Its not working for me.

class Controller extends BaseController { protected function addCookieToResponse($request, $response) { $request->session()->regenerateToken(); return parent::addCookieToResponse($request, $response); } }

Please or to participate in this conversation.