Search code examples
phplaravelsessionlaravel-5.3flash-message

How does Laravel unset session flash data?


I am currently trying to implement a way to flash session data similarly to how Laravel deals with flash data. I am aware that Laravel override the native session methods that are getting called by functions like session_start.

They seem to do this with the Http foundation package of Symfony by creating custom methods for open, read, write, etc. for the session. This is done by using session_set_save_handler:

http://php.net/manual/en/function.session-set-save-handler.php

By using that function you can implement your open logic for when you start a session or a session gets written to. But so far I can not find the direct logic in the Laravel codebase where flash data is being unset.

It would make sense to unset the flash data right before the write functionality of the session. This way you would unset it for future requests and will be sure it will only happen at the termination of your code.

Could anybody tell me how Laravel deals with session flash messages?


Solution

  • In the Illuminate\Session\Store class you can find the save method which is called when the sessions are stored. Aka the session_set_save_handler in essence.

    https://github.com/laravel/framework/blob/7acc98e112cce4e04f30c7ee4fc0a53dbc5c425b/src/Illuminate/Session/Store.php#L261

    On that line the $this->ageFlashData(); method is called.

    The method contains the following code

        $this->forget($this->get('_flash.old', []));
        $this->put('_flash.old', $this->get('_flash.new', []));
        $this->put('_flash.new', []);
    

    So on a page call all flash data is stored into _flash.new. When the sessions are saved all data in _flash.old will be cleared and everything stored in _flash.new is moved to _flash.old. The _flash.new is prepared to store new data for the next page call

    If you want to maintain flash messages, for example on an ajax call you can use the reflash() method in the session store which moves everything in the _flash.old back to the _flash.new