Sessions help remember information about a user while they browse your website. This way, the site can keep track of who they are and what they do.
Session basics in Laravel
<?php // Store data in session session(['key' => 'value']); // Get data from session $value = session('key', 'default'); // Remove data from session session()->forget('key'); // Clear all session data session()->flush();
Use the session() helper to easily work with session data.
You can store, retrieve, and remove data using simple methods.
<?php // Store user's name in session session(['username' => 'Alice']);
<?php // Retrieve username or default to 'Guest' $name = session('username', 'Guest');
<?php // Remove username from session session()->forget('username');
<?php // Clear all session data session()->flush();
This example shows three routes: one to set a session value, one to get it, and one to clear all session data. When you visit /set-session, it saves 'blue' as the color. Visiting /get-session shows the saved color. Visiting /clear-session removes all session data.
<?php use Illuminate\Support\Facades\Route; Route::get('/set-session', function () { session(['color' => 'blue']); return 'Session color set to blue'; }); Route::get('/get-session', function () { $color = session('color', 'no color set'); return "The session color is: $color"; }); Route::get('/clear-session', function () { session()->flush(); return 'Session cleared'; });
Sessions use cookies to link the user to their stored data.
Make sure your app has session middleware enabled to use sessions.
Session data is stored on the server, so it is safer than storing data in cookies.
Sessions keep user data while they browse your site.
Use session() helper to store, get, and remove data.
Clear sessions when you want to forget all stored info.