Evgeniy
Evgeniy

Reputation: 3349

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.

Upvotes: 2

Views: 3279

Answers (1)

Basheer Kharoti
Basheer Kharoti

Reputation: 4302

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']);

Upvotes: 2

Related Questions