Sessions provide a way to store information across multiple requests. In laravel, the session configuration file is stored in ‘app/config/session.php’. First of all, review the options available to you in this file. You will get some important documented information about where or how laravel store or manage session data. If you don’t specified your session driver, then the default session “driver” will be ‘file’. In that case, sessions are stored in
Retrieving Value from Session
There are 2 ways of working with session data in Laravel: the global
session() helper function and via type-hinted
Request instance on a controller method.
Request instance, you need to adduse
2nd argument of the above
get() method is the default value which will be returned if your specified key does not exist in the session.
Via The Global Session Helper:
Retrieving All Session Data
If you like to retrieve all the available data in the session, you can use the
Checking If an Item Exists In Session
To determine if a value is present in the session, you may use the
true if the value is present and if doesn’t present then returns
Storing Data in the Session
To store data in the session, you will typically use the
session helper method or the
put method of
Deleting Data from session
Deleting an item from session
forget method will remove the specifieditem from the session
If you first want to get the item value and then delete that item from the session, you can use the
The difference between the
forget() and the
pull() method is that,
forget() method will not return the value of the session but
pull() method will return it and delete that value from session.
Removing all items from session
If you would like to remove all items from the session, you may use the
Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:
Important Note(Session not save problem):
Session will be persisted at the proper end of the request cycle because laravel write session item to the specified driver at the end of request lifecycle.
It will not be saved when quitting the application(e.g.
dd() in application development) in the midway or an exception is occurred.
If you need store session item on the above situation or instantly after set the item in session, you need to call save method explicitly after put item in the session.