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

konarktriv7's avatar

How to get Middleware to fire?

Morning / Afternoon / Evening,

I'm wondering if someone else has encountered a way to ensure that Middleware is running on your tests.

We're currently doing a lot of Auth::check() & Auth::user()-> checks in our methods, but we're moving to using Middleware on our constructors like so;

public function __construct() { parent::__construct();

  $this->middleware(['auth']);

} This is working just fine in real use cases, but inside the tests it's not working as intended.

I have the following method;

public function method() { if(Auth::user()->can('doSomething')) { } }

When inside my test I do the following;

    $request = Request::create('/route', 'GET', []);

    $controller = new MyController();
    $response = $controller->method($request);

But the test is complaining that the Auth::user() is null. Now, this is actually my intention. I'm wanting to write a test to ensure that my method is not accessible by those not authenticated in my application.

I was under the impression that even with calling $controller->method(); the __construct() should still be called, and so the Middleware should then handle the situation, and return the correct response.

Am I missing something obvious? I feel like I'm going around in circles going crazy.

Any help would be appreciated. I have had a search online, and even here on Laracasts, but I am unable to find something related to wanting to explicitly make sure that middleware is running on my tests.

Update: My issue has been solved, thank you. https://discord.software/ https://omegle.onl/

0 likes
2 replies
drewdan's avatar

The middleware fires inbetween the requests and the response. Here, you're newing up a controllers, so that middleware won't fire.

If you did a feature test and did

$this->get('your-route-to-controller');

You would cause the middleware to fire.

I'd recommend a mixture of feature and unit tests to get the best coverage to make sure the middleware is firing.

In our tests we made a custom assertion to assert route has middleware, so we know it's there, even if it doesn't get fired when doing unit tests. And then we have a separate test for the middleware to make sure it does what we want it to do.

fylzero's avatar

@konarktriv7 I would argue that what you are trying to do is kind of leaning into the "testing the framework" and "unhappy path" approach. Which you really shouldn't need to do.

That said... is this kind of what you're looking for?

$response = $this->get('/route');
$response->assertForbidden();
24 likes

Please or to participate in this conversation.