Laravel Basic
Laravel Form
Laravel Database
Laravel Advance
A Session in Laravel is a way to store user data across multiple requests.
Since HTTP is stateless, sessions help in remembering data like login information, shopping cart items, preferences, etc., until the user closes the browser or logs out.
👉 Example: When a user logs in, their user ID is stored in the session so they stay logged in across different pages.
Sessions are configured in config/session.php
.
Important options:
driver
→ how session is stored (file, database, cache, cookie).lifetime
→ how long (in minutes) a session lasts.expire_on_close
→ whether to expire when browser closes.encrypt
→ whether to encrypt session data.Example (.env
):
SESSION_DRIVER=file SESSION_LIFETIME=120
Laravel supports different storage drivers for sessions:
storage/framework/sessions
.sessions
).👉 Use php artisan session:table
to create a sessions table for database
driver.
web.php (routes\web.php)
Route::get('/session_store', function () { session(['user_name' => 'john']); // Store user name in session return "Session Stored"; }); Route::get('/session_get', function () { return session('user_name'); // Get user name from session }); Route::get('/session_clear', function () { session()->forget('user_name'); // Remove user name from session return "Session Removed"; });
Output Store Session
Output Get Session
Output Remove Session
session(['user_id' => 1]); // Store user id session(['username' => 'John']); // Store name
OR
$request->session()->put('user_id', 1);
$userId = session('user_id'); $username = $request->session()->get('username');
if ($request->session()->has('user_id')) { // User is logged in }
$request->session()->forget('user_id'); // remove one key $request->session()->flush(); // remove all session data
To prevent session fixation attacks:
$request->session()->regenerate();
Flash data only lasts for the next request (useful for messages after redirect).
$request->session()->flash('status', 'Profile updated successfully!');
In Blade:
@if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif