A session stores data for one visitor across page loads — such as the logged-in user's id or a shopping cart.
Getting the session
Use the session() helper. It starts the session automatically.
Basic methods
session()->set('user_id', 5)or set several with an arraysession('user_id')orsession()->get('user_id')session()->has('user_id')session()->remove('cart')session()->destroy()— end the whole session (logout)
Flash data
Flash data lives for one request — perfect for messages after a redirect:
session()->setFlashdata('success', 'Saved!')(orredirect()->with('success', 'Saved!'))- In the view:
session()->getFlashdata('success')
Security
Call session()->regenerate() right after login. It gives a new session ID and prevents session fixation attacks.
Where sessions are stored
Settings are in app/Config/Session.php. The default FileHandler stores sessions in writable/session. You can switch to the database or Redis handler for multi-server sites.
Example
<?php
public function addToCart(int $productId)
{
$cart = session('cart') ?? [];
$cart[$productId] = ($cart[$productId] ?? 0) + 1;
session()->set('cart', $cart);
return redirect()->back()->with('success', 'Added to cart');
}
public function cartCount(): int
{
return array_sum(session('cart') ?? []);
}
// View (layout)
// <?php if (session()->getFlashdata('success')): ?>
// <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
// <?php endif ?>
Each click adds one of the product to the cart stored in the session. The "Added to cart" message shows once and disappears on the next page load.