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

mathewparet's avatar

Request identifies as Inertia for API requests even though Middleware is called while testing

I have a middleware that converts Inertia responses to non-inertia Json. This middleware is attached to all API routes.

I did this so that I could have a single controller for both API and HTTP requests. It works perfectly when testing on the browser and using Postman.

However, when I run it using php artisan test the middleware runs but fails to detect that it's an API request.

This is how I identify if the request is API or Inertia:

// AppServiceProvider.php

	public function boot(): void
    {
        $this->addIsApiMacroToRequest();
    }

    private function addIsApiMacroToRequest()
    {
        $request = app(Request::class);

        $request->macro('isApi', function () use ($request) {
            return $request->routeIs('api.*');
        });
	}

When running on the browser $request->isApi() returns false (as expected).

When running on postman $request->isApi() returns true (as expected).

When running via php artisan test, however, $request->isApi() returns false (it should return true).

My test case looks like this:

	public function test_application_can_be_created(): void
    {
        $this->actingAs($user = User::factory()->withPersonalTeam()->create());

        $response  = $this->post(route('api.applications.store'), ['name' => 'Test Application']);

        $this->assertDatabaseHas('applications', ['name' => 'Test Application']);

		// Fails below because it returns Inertia response and not API Json response.
        $response->assertJsonPath('name', 'Test Application');

        $response->assertJsonPath('active', false);
    }

This is how my middleware looks like:

0 likes
0 replies

Please or to participate in this conversation.