Search

Laravel Helper Function: session

November 20, 2016 —John Koster

session($key = null, $default = null)

The session function is a versatile function. It can be used to return the \Illuminate\Session \SessionManager instance, to set session values and to retrieve session values.

#Returning an Instance of \Illuminate\Session\SessionManager

To return an instance of the \Illuminate\Session\SessionManager class, set the $key parameter to null. If the $key parameter is set to null, the $default parameter is completely ignored.

1<?php
2 
3// Get the SessionManager instance.
4$sessionManager = session();

#Setting a Session Value

The session function allows setting session values directly by passing in an array of key/value pairs. The following example demonstrates this:

1<?php
2 
3// Settings two session values 'test' and 'test'2
4session([
5 'test' => 'A test message',
6 'test2' => 'Another test message'
7]);

Setting single session values is also possible:

1<?php
2 
3// Setting a single session value.
4session()->put('test3', 'Yet another test message');

#Retrieving a Session Value

Values can be retrieved with the session function by supplying a $key. To retrieve the test value from the earlier example the function call would look like so:

1<?php
2 
3// Retrieving the 'test' value.
4$value = session('test');

It is possible that a session value does not exist. When this is the case, the internal session mechanisms will return null. This can be overridden by supplying a value for the $default parameter:

1<?php
2 
3// Retrieving a value that does not exist.
4$valueThatDoesNotExist = session('does_not_exist', 'A default value');

In the above example the value of $valueThatDoesNotExit would be A default value.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.