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

abkrim's avatar
Level 13

actingAs return 404 in test, but endpoint work in production

I have started to implement tests for the api zone in my application, which I recently uploaded to Laravel 10.

I thought the code below should be fine, but it returns a 404 instead of a 200, on an endpoint that works perfectly in production if the user is logged in.

There are no roles or gates at the moment. They are required on all endpoints to be authenticated.

/** @test */
public function auth_user_can_see_town_halls()
{
     Sanctum::actingAs(User::factory()->create());

    $response = $this->get('api/v2/town-halls');

    $response->assertOk();
}

Also tries this that work in other routes

Sanctum::actingAs(User::factory()->create());
        $headers = ['Accept' => 'application/json'];

        $response = $this
            ->withHeaders($headers)
            ->get('api/v2/town-halls')
			->assertOk();
			// Responsde 404

Route

a route:list -vvv | grep town | grep GET
  GET|HEAD        api/v2/town-halls api.v2.town-halls.index › Api\Core\v2\TownHallApiController@index
  GET|HEAD        api/v2/town-halls/{town_hall} api.v2.town-halls.show › Api\Core\v2\TownHallApiController@show

Also after upgrade form laravel 9 to laravel 10 ? have upgrade guide sanctum and verify that in test database table personal_access_token has an expires_at field.

0 likes
1 reply
abkrim's avatar
Level 13

I use ChatGp response, and fails

 /** @test */
    public function auth_user_can_see_town_halls()
    {
        putenv('SANCTUM_STATEFUL_DOMAINS=localhost');
        $user = User::factory()->create();
        $token = $user->createToken('test-token')->plainTextToken;
        $headers = ['Authorization' => "Bearer $token"];
    
        $response = $this->withHeaders($headers)->get('/api/v2/town-halls');
        
        $response->assertOk();
    }

Please or to participate in this conversation.