Evgeniy Evgeniy - 3 years ago 160
PHP Question

How to provide Laravel session persistence, when pushing data?

I have a form and it send requests to the Laravel. Laravel controller catch requests and store data in session by push method, for example

$basename = pathinfo($path, PATHINFO_BASENAME);

if (!$request->session()->exists('upload')) {

$request->session()->put('upload', []);
}

$request->session()->push('upload', $basename);

var_dump($request->session()->get('upload'));


When form send two (or more) requests to Laravel, I expects to see in var_dump two (or more) values in array, but I see only one value. Why it can happening?

Thanks in advance!

PS. Simple example is showing that sequential push is works fine, and it create an array with two values.

$request->session()->put('upload', []);
$request->session()->push('upload', $basename);
$request->session()->push('upload', $basename);

var_dump($request->session()->get('upload'));


I think that the reason is that requests are async, and Laravel retrieve session values in the request begin (when session is empty). Each request push new value in empty array and store it.

Answer Source

You just need to use the keep method

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

session()->keep(['uploads']);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download