Kritim Yantra
Apr 02, 2025
Sessions are a crucial part of web development, allowing you to store user data across multiple requests. Laravel makes working with sessions simple and efficient. In this guide, we'll explore how sessions work in Laravel 12 and how you can use them in your applications.
A session is a way to store user-specific data on the server between HTTP requests. Unlike cookies (which are stored on the client side), sessions are stored securely on the server.
Common use cases for sessions include:
Laravel provides a clean, unified API for working with sessions. It supports several session drivers:
storage/framework/sessions
.By default, Laravel uses the file driver, which works well for most small to medium applications.
Session configuration is located in config/session.php
. Key settings include:
'driver' => env('SESSION_DRIVER', 'file'), // Default session driver
'lifetime' => 120, // Session lifetime in minutes
'expire_on_close' => false, // End session when browser closes
'encrypt' => false, // Encrypt session data
To change the session driver, update the .env
file:
SESSION_DRIVER=database
If using the database driver, run:
php artisan session:table
php artisan migrate
Laravel provides multiple ways to interact with sessions:
session()
Helper// Store data in session
session(['key' => 'value']);
// Retrieve data
$value = session('key');
// Default value if key doesn't exist
$value = session('key', 'default');
Session
Facadeuse Illuminate\Support\Facades\Session;
// Store data
Session::put('username', 'john_doe');
// Retrieve data
$username = Session::get('username');
// Check if a key exists
if (Session::has('username')) {
// Do something
}
// Remove a session key
Session::forget('username');
// Clear all session data
Session::flush();
Flash data is useful for one-time messages (e.g., success/error alerts).
// Store flash data
Session::flash('message', 'Login successful!');
// Retrieve flash data (available only in the next request)
$message = Session::get('message');
Let’s build a simple example where we store a user’s theme preference (light/dark mode).
php artisan make:controller ThemeController
routes/web.php
)use App\Http\Controllers\ThemeController;
Route::get('/theme', [ThemeController::class, 'show']);
Route::post('/theme', [ThemeController::class, 'update']);
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class ThemeController extends Controller
{
public function show()
{
$theme = session('theme', 'light'); // Default: light
return view('theme', compact('theme'));
}
public function update(Request $request)
{
$request->validate(['theme' => 'required|in:light,dark']);
session(['theme' => $request->theme]); // Store theme preference
return back()->with('success', 'Theme updated!');
}
}
resources/views/theme.blade.php
)<!DOCTYPE html>
<html lang="en" data-theme="{{ $theme }}">
<head>
<title>Theme Example</title>
<style>
[data-theme="light"] { background: #fff; color: #000; }
[data-theme="dark"] { background: #333; color: #fff; }
</style>
</head>
<body>
@if(session('success'))
<div class="alert">{{ session('success') }}</div>
@endif
<h1>Current Theme: {{ $theme }}</h1>
<form method="POST" action="/theme">
@csrf
<select name="theme">
<option value="light" {{ $theme == 'light' ? 'selected' : '' }}>Light</option>
<option value="dark" {{ $theme == 'dark' ? 'selected' : '' }}>Dark</option>
</select>
<button type="submit">Change Theme</button>
</form>
</body>
</html>
Now, when a user selects a theme, it will persist across requests!
'encrypt' => true
).Sessions in Laravel 12 are simple yet powerful. Whether you need to store user preferences, authentication status, or temporary messages, Laravel’s session system has you covered.
Start experimenting with sessions in your Laravel projects today! 🚀
Happy coding! 😊
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google