Session bags are small views over session arrays. They keep the API simple while making namespaced session data easy to test and reason about.
Related pages:
SessionBag implements SessionBagInterface.
$bag = $session->bag('preferences');
$bag->set('theme', 'dark');
$bag->set('density', 'compact');Available methods:
get(string $key, mixed $default = null): mixedset(string $key, mixed $value): statichas(string $key): boolremove(string $key, mixed $default = null): mixedpull(string $key, mixed $default = null): mixedreplace(array $values): staticall(): arrayclear(): staticisEmpty(): boolcount(): intgetIterator(): Traversable
remove() and pull() are aliases. Both return the removed value or the supplied default.
$root = $session->bag();The root bag points at the complete session payload. It is useful for generic tools, tests, and integrations that should not care whether data is namespaced.
$cart = $session->bag('cart');
$cart->set('items', [$itemId => 2]);Named bags are backed by arrays. If the namespace exists but contains a scalar value, the manager throws CorruptSessionDataException.
FlashBag implements FlashBagInterface.
$flash = $session->flash();
$flash->add('success', 'Saved.');
$flash->add('error', 'Payment failed.');Available methods:
add(string $type, mixed $message): staticset(string $type, array $messages): staticget(string $type, array $default = []): arraypeek(string $type, array $default = []): arrayhas(string $type): boolall(): arraypeekAll(): arrayclear(?string $type = null): staticcount(): intgetIterator(): Traversable
get() consumes messages for one type:
$messages = $session->flash()->get('success');all() consumes every message:
$messagesByType = $session->flash()->all();Use peek() or peekAll() when rendering or diagnostics should inspect messages without consuming them.
The default namespace is _flash.
$session->flash('_admin_flash')->add('warning', 'Admin mode enabled.');Custom namespaces are useful when independent packages share one session but should not consume each other's messages.