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

brandonferens's avatar

Laravel Dusk with Session Data

I have some middleware that checks certain things for the user. If the user is logged in normally, this stuff is loaded into the session. Logging them in with Dusk's handy loginAs method bypasses this functionality, which is fine. However I need to load some info manually into the session.

Normal phpunit testing allows me to do something like $this->withSession(['foo' => 'bar]);. But I can't figure out how to do this with Dusk. I would like to avoid logging in normally for every test, but if I can't get this solved, I will have to do that.

Anyone have some solutions?

0 likes
5 replies
djewett's avatar

@brandonferens were you able to find a solution for this? We have a similar need and have not figured out how to do this with dusk.

brandonferens's avatar

@djewett No, I didn't find any solutions. It's been awhile, so I don't remember which code I was working on as to my ultimate workaround.

swan03's avatar

Its simple, You need to create route for set session variable.

Route::get('set-session',function(){ session(['warehouse'=>2031]); });

Write a first line to in those test case where ever you required session.

$this->browse(function ($browser) { $browser->visit('set-session'); });

arielenter's avatar

@swan03 I've tried setting up a route with a view the way you are suggesting, but unfortunately browser reports 404. Is it just me?

Please or to participate in this conversation.