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

enikola's avatar

Session variable is not cleared when downloading a file

Hi all,

I'm running Laravel 5.4 and "maatwebsite/excel": "~2.1.0" to provide a CSV download. The content of the download is controlled by a session variable. Everything is set up and is working beautifully. Except one issue: the session variable is not cleared

$request->session()->forget('sessionvar');

Excel::create(time(), function($excel) use($data) {
  $excel->sheet('data', function($sheet) use ($data) {
    $sheet->fromArray($data, null, 'A1', false, false);
  });
})->download('csv')

Download works without a problem. However after reloading the page sessionvar has not been removed from the session.

What is going on? Any hint is appreciated.

Thank you.

0 likes
1 reply
enikola's avatar
enikola
OP
Best Answer
Level 1

The documentation states: For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser. If you define a terminate method on your middleware, it will automatically be called after the response is sent to the browser.

So to solve the issue I had to

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

Please or to participate in this conversation.