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

phpMick's avatar
Level 15

Session data lost after redirect.

I'm pretty sure I have seen this before but I can't remember how I solved it.

My session data is getting lost when I do a redirect.

 if($request->tenant ==="-1") {//all tenants selected
            session()->put('selectedTenant',"-1");
}


return redirect(url()->previous());

I tried adding this but It didn't help:

$request->session()->save();

In this function I can check and the session variable is set correctly. If i stop the code after the redirect, the session has restored to it's previous value.

Mick

0 likes
3 replies
DavidPetrov's avatar
Level 2

Are you sure you're not having a middleware somewhere else that's rewriting the session key and setting a default value? Usually, when you use the session's put method, information should be stored for the lifetime of the session unless something rewrites or resets it. On another occasions, I've also had problems with the default session middleware and positioning other custom middlewares around it in the Kernel.php file. There are a lot of possible scenarious that could cause session termination on given urls when other middlewares are active. I suggest you have a closer look at your middleware net and investigate there.

phpMick's avatar
Level 15

@davidpetrov thanks, great detective work.

I do indeed have some middleware which ensures a valid tenant is selected.

In this instance I was selecting -1 to signify 'All Tenants'. My middleware was failing to find a valid tenant with this id, so it sets it to be the users 'home tenant' (and overwriting the -1 I had put in session with 2).

:-)

Please or to participate in this conversation.