Sessions
The HTTP protocol is inherently stateless. If you want to maintain some data between requests, you will need to use the Session.
Configuration
The Session is configured using the config/session.php
file. By default Lumberjack is configured to store all session data as files on the disk.
Usage
If you're using the global helpers, you can use the session()
helper function instead of the Session
facade. For example:
Retrieving Data
The primary way to work with session data is via the Session
Facade:
You can also pass an optional second parameter to use as a default in the instance the requested key doesn't exist:
Retrieving All Session Data
You can use the all()
function if you wish to retrieve all the session data:
Determine If An Item Exists In The Session
You can check if a specific key is stored in the session using the has()
function:
Retrieve and remove
If you wish to remove an item from the session but also retrieve it's current value, you can use the pull()
function:
Storing Data
To store data into the session you use the put()
function:
You can pass in an array of key/value pairs to add multiple items.
Adding items to an array
If you have an array in your session, you can add new data to it by using the push()
function:
Flash Data
There are times when you only want to keep session data for the next request, e.g. form values when a validation error occurs.
You can achieve this easily in Lumberjack using the flash()
function:
You can pass in an array of key/value pairs to flash multiple items.
If you later decide that you need the data to persist in the session you can do this in two ways. Use the keep()
to select specific keys to retain or reflash()
to store all flash data for an additional request.
Deleting Data
To remove a specific item from the session you use the forget()
method.
To remove multiple items from the session you can pass an array of keys into the forget()
method.
To remove all items from the session, you can use the flush()
method.
Adding Custom Storage Drivers
Lumberjack is capable of using multiple different drivers for session storage. The default and only driver provided in the core is the file
driver, which saves all session data to disk.
It is simple to implement and register a new driver though.
Implement the driver
Start by creating a class that implements the standard PHP SessionHandlerInterface that provides the storage functionality you require:
Register the driver
To register the new driver you need to use a Service Provider. If you don't want to create a new provider you can use the AppServiceProvider
which can be found in app\Providers\AppServiceProvider.php
.
Registration is done by calling extend()
on the Session facade:
After this it's just a matter of updating the driver
value in config/session.php
to match the key you passed to extend()
, in this instance this would be database
.
Last updated