Working with Laravel Sessions

January 30, 2018


Working with Laravel Sessions

We all know that HTTP driven web applications are stateless in nature. Therefore, sessions play an important role in storing user information across multiple requests. Laravel provides various backend drivers such as a file, APC, cookie and database. It also supports famous backends like Redis and Memcached.

The default driver is the file as it is lightweight and convenient for many applications. Though for production applications, Redis or Memcached can be considered for improved session performance. This and other session configuration settings can be updated from config/session.php file.

# Store Data in Session

There are two ways of operating sessions in Laravel. The global session helper or via Request instance. We can use put() method of session helper to store the data in the session.

// Global helper
session(['key' => 'value']);
// Request instance
$request->session()->put('key', 'value');

# Pushing Session Values to Array

The push() method of Request instance in used to push a fresh value to an array session.

$request->session()->push('key', 'value');

# Retrieve Session Data

# Retrieve Session by Key:

As with storing data, we can retrieve session data in same two ways, i.e., Session helper and Request Instance.

// Retrieve with Global Helper
$result = session('key');
// Retrieve with Request Instance
$result = $request->session()->get('key');

# Retrieve All:

All method on request instance can be used to retrieve all the session stored in the application as:

$result = $request->session()->all();

# Retrieve Session with Default Argument:

Also, while retrieving data, there may be an instance where session doesn’t really exist and thus the session value wouldn’t be retrieved. In such cases, we can return the default value specified as:

$request->session()->get('key', 'default value');
// Closure 

$result = $request->session()->get('key', function () {
    return 'default value';

We can achieve this with global session helper as well:

// Default value with Global Helper
$result = session('key', 'default value');

# Delete Session

We can remove application session with forget and flush methods. Difference between the both is that forget removes a single key from session while flush deletes all session key-value pairs. Here’s how:

//remove specific key
//remove all sessions


Sessions are very crucial for any web application and therefore knowing all its use cases can be helpful. In this post we tried and covered all such cases. Go ahead and use them now!

Questions & Comments:

Thank you for reading. If you encounter any errors while dealing with sessions in Laravel, share them in the comment section below.

Leave a comment

Your email address will not be published. Required fields are marked *