Laravel Session Management: Configuration, Drivers, and Usage
This guide explains how Laravel handles session storage across HTTP requests, covering configuration files, built‑in drivers such as file, cookie, database, Memcached and Redis, custom driver creation, and common session operations like retrieving, storing, flashing, and regenerating IDs, with code examples throughout.
Introduction
Since HTTP‑driven applications are stateless, the Session component provides a way to store user information across multiple requests. Laravel offers a readable API for various built‑in drivers, including popular options like Memcached, Redis, and database storage.
Configuration
The session configuration resides in config/session.php. By default Laravel uses the file driver, storing sessions in storage/framework/sessions. For production you may switch to memcached or redis for better performance.
Available Drivers
file– stores sessions in the file system. cookie – stores encrypted sessions in cookies. database – stores sessions in a relational database table. memcached / redis – stores sessions in high‑speed cache stores. array – stores sessions in a PHP array (non‑persistent, useful for testing).
Tip: The array driver is typically used for testing to avoid persisting session data.
Driver Prerequisites
Database
When using the database driver you must create a sessions table. A typical migration schema is:
Schema::create('sessions', function ($table) {
$table->string('id')->unique();
$table->unsignedInteger('user_id')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->text('payload');
$table->integer('last_activity');
});You can generate this migration with the Artisan command php artisan session:table followed by php artisan migrate.
Redis
Before using Redis as a session driver, install the predis/predis package via Composer. Then configure the Redis connection in config/database.php and specify the connection name in config/session.php under the connection option.
Using Sessions
Retrieving Data
Laravel provides two main ways to access session data: the global session() helper and the Request instance injected into a controller. Example using a controller method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show the profile for the given user.
*/
public function show(Request $request, $id)
{
$value = $request->session()->get('key');
// ...
}
}You can provide a default value as the second argument to get, or a closure that will be executed when the key does not exist.
$value = $request->session()->get('key', 'default');
$value = $request->session()->get('key', function () {
return 'default';
});Global Helper
The session() helper can also retrieve and store values:
Route::get('home', function () {
// Retrieve a value
$value = session('key');
// Retrieve with default
$value = session('key', 'default');
// Store a value
session(['key' => 'value']);
});Tip: Using the request instance or the global session() helper are functionally equivalent and can both be tested with assertSessionHas .
Getting All Session Data
Use the all() method to retrieve the entire session array:
$data = $request->session()->all();Checking Existence
Use has('key') to determine if a non‑null value exists, or exists('key') to check for a key even if its value is null:
if ($request->session()->has('users')) { /* ... */ }
if ($request->session()->exists('users')) { /* ... */ }Storing Data
Store values with put('key', 'value') or the global helper:
$request->session()->put('key', 'value');
session(['key' => 'value']);Pushing to an Array
The push('user.teams', 'developers') method adds a new element to an array stored in the session.
$request->session()->push('user.teams', 'developers');Pulling (Retrieve & Delete)
$value = $request->session()->pull('key', 'default');Flash Data
Flash data persists only for the next request. Use flash('status', 'Task was successful!'). To keep flash data for an additional request, call reflash() or keep(['key1', 'key2']).
$request->session()->flash('status', 'Task was successful!');
$request->session()->reflash();
$request->session()->keep(['username', 'email']);Deleting Data
Remove a single key with forget('key') or multiple keys with an array. Use flush() to clear the entire session.
$request->session()->forget('key');
$request->session()->forget(['key1', 'key2']);
$request->session()->flush();Regenerating Session ID
Regenerate the session identifier to prevent session fixation attacks using regenerate(). Laravel’s authentication controller does this automatically; otherwise call it manually.
$request->session()->regenerate();Adding a Custom Session Driver
Implementing the Driver
Your custom driver must implement SessionHandlerInterface. Below is a skeleton for a MongoDB driver:
<?php
namespace App\Extensions;
class MongoSessionHandler implements \SessionHandlerInterface
{
public function open($savePath, $sessionName) {}
public function close() {}
public function read($sessionId) {}
public function write($sessionId, $data) {}
public function destroy($sessionId) {}
public function gc($lifetime) {}
}Tip: Laravel does not provide a dedicated extensions directory; you can place your custom handler in any folder, such as app/Extensions .
Registering the Driver
Register the driver in a service provider using Session::extend() inside the boot method:
<?php
namespace App\Providers;
use App\Extensions\MongoSessionHandler;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;
class SessionServiceProvider extends ServiceProvider
{
public function register() {}
public function boot()
{
Session::extend('mongo', function ($app) {
return new MongoSessionHandler();
});
}
}After registration, set 'driver' => 'mongo' in config/session.php to activate the custom driver.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
