Laravel session() Guide: Working with Sessions A to Z | DCSoft Tech
- Home
- Laravel session() Guide: Working with Sessions A to Z | DCSoft Tech
Laravel provides three primary methods to interact with sessions, depending on your code context:
Commonly used inside Controller methods:
use Illuminate\Http\Request;
public function store(Request $request)
{
$value = $request->session()->get('key');
}
Session FacadeCan be called anywhere within your application:
use Illuminate\Support\Facades\Session;
Session::put('key', 'value');
$value = Session::get('key');
session() Global HelperThe most concise and common approach:
// Store or retrieve a value
session(['key' => 'value']);
$value = session('key');
// Using the session() helper
session(['user_id' => 123]);
// Using the put method
session()->put('cart.count', 5);
// Push a new element into an array session value
session()->push('user.teams', 'developers');
// Retrieve a value with a default fallback if the key doesn't exist
$name = session('name', 'Guest');
// Get all data from the session
$data = session()->all();
// Check if a key exists (even if its value is null)
if (session()->has('user_id')) {
// ...
}
// Check if a key exists and is not null
if (session()->exists('user_id')) {
// ...
}
// Forget a specific key
session()->forget('user_id');
// Forget multiple keys
session()->forget(['user_id', 'role']);
// Remove all session data for the current request
session()->flush();
Flash data is useful when you want to store session items only for the subsequent HTTP request, after which it automatically deletes itself. This is commonly used for short-lived status notifications (Flash Messages).
// Store flash data
session()->flash('success', 'Data updated successfully!');
// Reflash all flash data for one more request
session()->reflash();
// Keep specific flash data keys for one more request
session()->keep(['success', 'message']);
Displaying flash notifications inside a Blade template is straightforward:
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
config/session.php)Laravel supports several session storage drivers, defined inside config/session.php:
file: Stores sessions in storage/framework/sessions (default for local development).
database: Stores sessions in a sessions database table (ideal for scaling across multi-server setups).
redis / memcached: Fast, memory-based cache stores.
cookie: Stores encrypted sessions directly in browser cookies.
You can configure your preferred driver quickly in the .env file:
SESSION_DRIVER=database
SESSION_LIFETIME=120
Mastering session management in Laravel helps you build reliable authentication, shopping carts, and flash messages while maintaining security and performance.