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

abdulmabud's avatar

Session return wrong value.

When I write this line of code

public function cartAdd(Request $request){

    $request->session()->put('key', 'value 1');
    $output = $request->session()->get('key');
     dd($output);
}

Then output "value 1"

But when I comment one line code which set the session value

public function cartAdd(Request $request){

  // $request->session()->put('key', 'value 1');
    $output = $request->session()->get('key');
      dd($output);
}

Then output

"this is key 1"

This is my previous session value. What's wrong with this. This time output should be "value 1"

0 likes
5 replies
ahkeravi's avatar

try this one @abdulmabud

public function cartAdd(Request $request){

session(['key' => 'value 1']);
$output = $request->session()->get('key');

 dd($output);

}

Sinnbeck's avatar

Why are you trying to get the session in the same request that you are in? Normally sessions are used to store data between requests.

If you are using the cookie driver, I believe it will not be persisted until sent to to browser (the end of the request)

abdulmabud's avatar

@sinnbeck

I found two solutions.

No 1. Remove dd() method. Because of dd() request not complete and it's not working.

No 2. Save the session using $request->session()->save(); .

Both are working for me.

Am I right @sinnbeck ??

Rjonwal's avatar

I'm also facing the same issue, firstly A session variable is created with some values, and after that, I'm updating the values using the put method. but when I'm trying to get session values on another page, that old values are coming there. How can I get the new values?

Please or to participate in this conversation.