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

dericcain's avatar

Testing session variable after authenticated

When a user has successfully authenticated, I am adding a session variable to make API calls. I want to be able to test this but I am not finding a way to do so. Here is what I have tried.

/** @test */
    function a_users_api_token_is_stored_in_session_after_login()
    {
        $user = factory(User::class)->create();
        $user = User::find($user->id);

        $this->actingAs($user)
            ->visit('/')
            ->assertSessionHas('api_token');
    }

This always comes back as false. However, when I manually log in and look at my session variables, it works as expected.

Anyone know how to do this?

0 likes
3 replies
SaeedPrez's avatar

Try below code instead of ->actingAs($user)..

auth()->login($user);

$this->visit('/')->andSoOn()..
dericcain's avatar

@SaeedPrez Thanks for the help, but it is still not working. Just so you can see where I'm storing the session variable, here is the code in the AuthController.

public function authenticated()
 {
        Session::put('api_token', Auth::user()->api_token);
 }

Again, this is working if I manually login, so I'm not sure why the test is not working.

SaeedPrez's avatar

@dericcain aha, I believe that method is only used if you go through the actual login process.

You could do the whole login acceptance test, something like..

        $this->visit('/login')
            ->see('E-Mail Address')
            ->type('[email protected]', 'email')
            ->type('test123', 'password')
            ->press('Login')
            ->seePageIs('/dashboard')
            ->assertSessionHas('api_token');
1 like

Please or to participate in this conversation.