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

princelionelnzi's avatar

TokenMismatchException error with PHPUnit after upgrade

I just upgrade from Laravel 5.3 to 5.4 then I move to 5.5.

After that, I wrote this test:

    /** @test */
    public function it_adds_a_new_address_to_the_user_profile()
    {
        $this->withoutExceptionHandling();

        $user = factory(User::class)->create();
        $this->be($user);

        $address = factory(Address::class)->make()->toArray();

        $this->post(route('address.store'), $address);

        $this->assertDatabaseHas('addresses', $address);
    }

The issue is that, anytime I run this test I get TokenMismatchException error. But I have another project which was initially created with Laravel 5.5 and the same test does not give any TokenMismatchException error.

Kindly help me fix this error. Thanks

0 likes
1 reply
arthurvillar's avatar

It looks like there is an issue with the CSRF field that Laravel uses to validate post requests. First, I would go to this file

vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php

and edit this function

    protected function tokensMatch($request)
    {
        // Add this line
        if (env('APP_ENV') === 'testing') {
            return true;
        }

        // Leave the rest as it is
        $token = $this->getTokenFromRequest($request);

        return is_string($request->session()->token()) &&
               is_string($token) &&
               hash_equals($request->session()->token(), $token);
    }

If that doesn't work, then you can disable the CSRF verification on a specific route by going here

App\Http\Middleware\VerifyCsrfToken.php

and including the route in this variable

    protected $except = [
        // include your route here
    ];

Ultimately running this command on the terminal can also help

php artisan config:clear

Please or to participate in this conversation.