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

Rens's avatar
Level 1

Session values lost after redirect

I have to issue a redirect using the native PHP way, as I'm depending on an external library. When I write values to the session before doing the redirect using header(), they are lost after the request has been redirected.

function someLibraryFunction() {

    $request = request();
    $request->session()->put('foo', 'bar');

    // This does work: echo redirect('/get');
    // But this doesn't:

    header('Location: /get');
    exit;
};

// These are web routes that have the relevant session middleware applied to them.

Route::get('/set', function (Request $request) {

    someLibraryFunction();
});

Route::get('/get', function (Request $request) {

    print_r($request->session()->all()); // 'foo' is not set here.
});

NOTE: I've verified that session()-getId() is the same before and after the redirect.

Any ideas?

0 likes
5 replies
petrit's avatar

use global helper

session()->put('blah', 'testvar'); 

and will get it

session()->get('blah);
1 like
Rens's avatar
Level 1

Doesn't make a difference unfortunately

jlrdw's avatar

This issue has come up many times before I forget what the exact solution was but do a Google Search and it was answered previously. It seems this issue pops up monthly again sorry I do not remember what the solution was. I do remember one solution had to do with the order of the routes.

Rens's avatar
Rens
OP
Best Answer
Level 1

Calling $request->session()->save() before redirecting fixes it. Apparently, actual writing to the session is delayed.

5 likes
albertoelias123's avatar

https://laravel.com/docs/master/session#flash-data

"If you need to keep your flash data around for several requests, you may use the reflash method, which will keep all of the flash data for an additional request. If you only need to keep specific flash data, you may use the keep method:"

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


$request->session()->keep(['username', 'email']);

Please or to participate in this conversation.