Skip to content

Laravel Session — Session Management and Drivers

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Laravel Session. We cover key concepts, practical examples, and best practices to help you master this topic.

Laravel session management supports file, database, Redis, Memcached, and cookie drivers with flash data, session helpers, encryption, and custom session handlers.

What You'll Learn

By the end of this tutorial, you'll configure session drivers, store and retrieve session data, use flash sessions for one-time messages, secure sessions, and create custom drivers.

Why Sessions Matter

Sessions maintain state across HTTP requests for user authentication, shopping carts, flash messages, and form input persistence.

Real-World Use

An e-commerce site uses Redis sessions for fast access across load-balanced servers. Flash sessions provide one-time success messages after form submissions.

Session Path

flowchart LR
  A[Laravel Framework] --> B[Session]
  B --> C[Drivers]
  B --> D[Flash Data]
  B --> E[Security]
  B --> F[Custom Drivers]
  B --> G{You Are Here}
  style G fill:#f90,color:#fff

Session Configuration

Configure session driver and settings.

<?php
// config/session.php
"driver" => env("SESSION_DRIVER", "file"),
"lifetime" => 120,
"expire_on_close" => false,
"encrypt" => false,
"files" => storage_path("framework/sessions"),
"connection" => env("SESSION_CONNECTION"),
"table" => "sessions",
"store" => env("SESSION_STORE"),
"lottery" => [2, 100],
"cookie" => env("SESSION_COOKIE", "laravel_session"),
"path" => "/",
"domain" => env("SESSION_DOMAIN"),
"secure" => env("SESSION_SECURE_COOKIE"),
"http_only" => true,
"same_site" => "lax",

Session Operations

Store and retrieve session data.

<?php
// Store data
session(["cart.items" => $items]);
session()->put("user.preferences.theme", "dark");
request()->session()->put("flash.message", "Saved successfully");
// Retrieve data
$cart = session("cart.items", []);
$theme = session()->get("user.preferences.theme", "light");
$all = session()->all();
// Check existence
if (session()->has("user.id")) {}
if (session()->exists("user.preferences")) {} // Includes null values
// Remove
session()->forget("cart");
session()->flush(); // Clear all session data

Flash Session

Store one-time data that expires after the next request.

<?php
// Flash data for next request
session()->flash("status", "Profile updated!");
session()->flash("error", "Validation failed.");
// Flash with reusable data
session()->reflash();
session()->keep(["username", "email"]);
// Flash input
old("email"); // Retrieves flashed input from previous request
// In Blade
@if (session("status"))
    <div class="alert alert-success">{{ session("status") }}</div>
@endif

Database Sessions

Store sessions in the database for persistence.

php artisan session:table
php artisan migrate
<?php
// config/session.php
"driver" => "database",
"connection" => "mysql",
"table" => "sessions",
// Manually query sessions
use Illuminate\Support\Facades\DB;
$sessions = DB::table("sessions")
    ->where("last_activity", ">", now()->subHour()->timestamp)
    ->get();
foreach ($sessions as $session) {
    $data = unserialize(base64_decode($session->payload));
}

Session Security

Secure session handling and regeneration.

<?php
// Regenerate session ID after login
$request->session()->regenerate();
// Invalidate entire session
$request->session()->invalidate();
// Regenerate token
$request->session()->regenerateToken();
// CSRF protection
csrf_token(); // Get current token
// Session fixation prevention
auth()->login($user, remember: true);
auth()->logout();
session()->invalidate();
session()->regenerateToken();

Common Mistakes

1. Storing Large Objects in Session

Session data is serialized on every request. Large objects slow down response times.

2. Not Using Flash for One-Time Messages

Using put() for status messages persists across requests. Use flash() for one-time data.

3. Ignoring Session Expiry

Long-lived sessions without activity timeout increase security risks.

4. File Sessions on Load-Balanced Servers

File sessions do not work across servers. Use Redis or database sessions in clustered environments.

5. Not Regenerating Session ID After Login

Session fixation attacks exploit unchanged session IDs. Always regenerate after auth.

Practice Questions

1. What is the difference between put() and flash()?

put() persists until deleted. flash() expires after the next request.

2. How do you regenerate the session ID?

Use $request->session()->regenerate().

3. What session driver works across load-balanced servers?

Redis or database sessions, not file sessions.

4. How do you retrieve flashed input?

Use old("fieldname") helper function.

5. Challenge: Implement a shopping cart using session.

<?php
class CartService {
    public function addItem(int $productId, int $quantity): void {
        $cart = session()->get("cart", []);
        if (isset($cart[$productId])) {
            $cart[$productId] += $quantity;
        } else {
            $cart[$productId] = $quantity;
        }
        session()->put("cart", $cart);
    }
    public function getItems(): array {
        return session()->get("cart", []);
    }
    public function clear(): void {
        session()->forget("cart");
    }
}

FAQ

What is the best session driver for production?

Redis for performance and scalability across servers. Database for reliability.

How long do sessions last?

Default lifetime is 120 minutes. Controlled by session.lifetime config.

Can I use multiple session drivers?

Laravel uses one driver at a time. Store additional data in cache.

What is CSRF token and how does it relate to sessions?

CSRF token is stored in session and validated on POST requests for security.

How do I delete expired sessions?

Laravel handles expiration. Database sessions need periodic cleanup via session:gc command.

Mini Project: Flash Notification System

Build a flash notification system with session.

<?php
class Flash {
    public static function success(string $message): void {
        session()->flash("flash.type", "success");
        session()->flash("flash.message", $message);
    }
    public static function error(string $message): void {
        session()->flash("flash.type", "error");
        session()->flash("flash.message", $message);
    }
    public static function get(): ?array {
        if (!session()->has("flash.message")) return null;
        return ["type" => session("flash.type"), "message" => session("flash.message")];
    }
}

What's Next

Laravel Cache Deep Laravel Broadcasting Laravel Notifications

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro