April 14, 2018 —John Koster
The session
function can be used to resolve the "\Illuminate\Session\SessionManager" instance from the service container, retrieve session values, and even set new session values. These different behaviors are controlled by the types, and number, of arguments supplied to the function call.
The signature of the session
function is:
1function session(); 2 3function session([ 4 $key, 5 $value = null 6]); 7 8function session( 9 $key = null,10 $default = null11);
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// Get the SessionManager instance.2$sessionManager = session();
The session
function allows setting session values directly by passing in an array of key/value pairs. The following example demonstrates this:
1// Settings two session values 'test' and 'test2'2session([3 'test' => 'A test message',4 'test2' => 'Another test message'5]);
Setting single session values is also possible:
1// Setting a single session value.2session()->put('test3', 'Yet another test message');
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// Retrieving the 'test' value.2$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// Retrieving a value that does not exist.2$valueThatDoesNotExist = session('does_not_exist', 'A default value');
In the above example the value of $valueThatDoesNotExit
would be A default value
.
∎
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.