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

ismail_bourbie's avatar

Test Session

Is it possible to test if a session is being regenerated after authentication to ensure that no one can remove this line of code?

 if (Auth::attempt($credentials)) {
            // $request->session()->regenerate();
            return redirect()->intended('/profile');
        }														
0 likes
2 replies
tisuchi's avatar

@ismail_bourbie Yes, you can do that.

Try this:

 /** @test */
    public function session_is_regenerated_after_authentication()
    {
        $user = User::factory()->create([
            'password' => bcrypt($password = 'i-love-laravel'),
        ]);

        // Start a session
        Session::start();

        // Save the current session ID
        $oldSessionId = Session::getId();

        $response = $this->post('/login', [
            'email' => $user->email,
            'password' => $password,
        ]);

        // Assert they're authenticated
        $response->assertRedirect('/profile');
        $this->assertAuthenticatedAs($user);

        // Check that the session ID has changed
        $this->assertNotEquals($oldSessionId, Session::getId());
    }
1 like
ismail_bourbie's avatar

@tisuchi try it, but not working, i think because: Auth::attempt() regenerate the id, the id regenerated twice by attempt() and by session()->regenerate()

Please or to participate in this conversation.