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

H4L1M's avatar
Level 1

Testing Session destruction

I have this middleware that checks if the user has been banned.

        if (auth()->check() && !$request->user()->status) {

            $request->session()->flush();
            return redirect('login');
        }
        return $next($request);

its for users that get banned while online , cause offline ones are blocked from login it works well ; but am trying to write a test for it

    public function session_destroyed_on_user_restriction()
    {
        Auth::login($this->activeUser);

        $this->assertAuthenticatedAs($this->activeUser);

        User::where('id', $this->activeUser->id)->update(['status' => false]);

        $this->activeUser = User::findOrFail($this->activeUser->id);

        $this->assertEquals($this->activeUser->status, '0');

        $response = $this->get(route('dashboard'));
        $response->assertRedirect('login');

        $this->assertGuest();
    }

any idea why its failing on

        $response->assertRedirect('login');

        $this->assertGuest();

thnks

0 likes
3 replies
LaryAI's avatar
Level 58

The test is failing because the session is not being destroyed. To test session destruction, you can use the assertSessionHasNoErrors method. Here's an updated version of the test:

public function session_destroyed_on_user_restriction()
{
    Auth::login($this->activeUser);

    $this->assertAuthenticatedAs($this->activeUser);

    User::where('id', $this->activeUser->id)->update(['status' => false]);

    $this->activeUser = User::findOrFail($this->activeUser->id);

    $this->assertEquals($this->activeUser->status, '0');

    $response = $this->get(route('dashboard'));

    $response->assertRedirect('login');

    $this->assertGuest();

    $this->assertSessionHasNoErrors();
}
Snapey's avatar

my thoughts are that the user model is already cached as the authenticated user ?

H4L1M's avatar
Level 1

@Snapey any thoughts on how to make him pass by that midleware to flush his session?

it works on bowser , sessions get flushed and users get redirected to login to see that they are banned

Please or to participate in this conversation.