Laravel 5: HTTP Layer – Sessions

Laravel 5: HTTP Layer – Sessions

Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests.

See also:

  • global session() helper method here
  • also read more here – scroll down to session
  • you may also see Laravel docs here
If you start a new project and this project from a jump start is not going to be very busy, and you are not Redis expert, put your sessions into DB table. You can always switch later.
If your site is going to be rather slow and you do not care to query your sessions, you may use default file based session, but DB is better.

Lets look at session commands.

Prepare DB based sessions

Use Artisan to set db session table and migrate it:

This is what you get:

Then you transfer it to database:

Request based commands
Get data for selected key

Get selected key – you may use ‘dot notation’, e.g. ‘key.subkey’:

Get data for selected key, and return some arbitrary default, if key does not exists

Get selected key and just in case it does not exist, set default value:

You can use Closure. You can inject some object into a closure and if session does not have key specified, you can use object, do some magic with it and return needed default value:

Get entire session data

Check if value exists for given key and is not NULL

Check, if some value exists (by its key), and if it does, you may do something.
Below method returns true, if value for specified key exists and is NOT null:

Check if value exists for given key REGARDLESS if it is NULL

Store data

Store data in session held array using dot.notation

Pull data from session and delete it from session

Store some data in session for a given request

Keep data for another request

Keep just specific data from flash to another request – sort of partial reflash()

Delete session data for given key

Remove entire session data

Regenerating The Session ID


Get value from session

Store value in session

When the helper is called with an array of key / value pairs, those values will be stored in the session.

Another way to store data