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

sam_bennett's avatar

Session lost during testing

I have hit a brick wall with my testing. I have a helper method in app/helpers.php that accesses the authenticated user. However, during my tests this is always null. If I dd() the auth()->user() in the controller when doing the test I can see the value. But anything in blade or this helper file it always returns null. Even session()->all() is a completely empty array.

I do have SESSION_DRIVER=file in the .env.testing and phpunit.xml but no matter what it is still null.

0 likes
17 replies
Sinnbeck's avatar

Can you start by showing the test and maybe the controller method + helper function?

sam_bennett's avatar
// TestController.php
class TestController extends Controller
{
	public test()
	{
		dd(session()->all());
	}
}

This then works as expected when doing get('/')->assertOk(). But in app/helpers.php I have.

// TestController.php
class TestController extends Controller
{
	public test()
	{
		customer();
	}
}

// app/helpers.php
function customer()
{
		dd(session()->all());
}

This then is []. If I was to do auth()->user() in the controller I get the user when doing actingAs() but in the same helper method it becomes null.

Sinnbeck's avatar

@sam_bennett I just made the same set up and this gives me the user

function customer()
{
		dd(auth()->user());
}
Sinnbeck's avatar

@sam_bennett How are you loading your helpers.php ? This is mine

"autoload": {
        "files": [
            "app/helpers.php"
        ],
//etc
sam_bennett's avatar

@Sinnbeck Yeah, everything else is working fine but it's like the helper file doesn't have access to session

Sinnbeck's avatar

@sam_bennett That is really weird. A helper function is just a function. It shouldn't be anything special. I don't suppose it is on github publicly or you are able to make a minimal reproducible repo ?

click's avatar

What if you try the array session_driver? For testing that should be good enough.

sam_bennett's avatar

@click I did have that originally and it was not working then, so I changed it to file to be the same as the normal .env but it made no difference.

click's avatar

@sam_bennett And if you output the name of the driver, is it the same for both of the cases (in the controller & in your method in helpers.php?

dd(session()->getDefaultDriver());
click's avatar

@sam_bennett and I assume it is the same in the controller?

So the be 100% sure;

You call your controller via a unit test (via an api call)

public function test()
{
    dump(session()->all());
    dump(customer());
}
// app/helpers.php
function customer()
{
		return session()->all();
}

This gives you one time a filled array and once an empty array?

If that is the case I only have one suggestion: "Did you try turning it off and on again" as it is a strange case.

1 like

Please or to participate in this conversation.