Session Data

Reading and Writing Session Data

Use $request->session() in routes and controllers, or the session() helper anywhere: session('key') reads and session(['key' => 'value']) writes. Keys use dot notation, and the same Store works in php artisan tinker:

The session API, run in tinkerPHP
$s = session()->driver();
$s->start();
$s->put(['cart.items' => ['BK-PHP-01'], 'coupon' => null]);
$s->push('cart.items', 'BK-SQL-01');
$s->increment('cart.count', 2);
echo json_encode([$s->get('coupon', 'none'), $s->get('gift', fn () => 'none'),
    $s->has('coupon'), $s->exists('coupon'), $s->missing('gift')]), PHP_EOL;
echo json_encode($s->pull('cart.items')), ' ', json_encode($s->only(['cart'])), PHP_EOL;
Output
[null,"none",false,true,true]
["BK-PHP-01","BK-SQL-01"] {"cart":{"count":2}}

A default (a value, or a closure run only when needed) applies to a missing key, not to one stored as null. has() is false for both, and exists() tells them apart. pull() reads and deletes, forget() takes one key or several, and flush() empties everything, even _token. $request->session()->cache() offers the cache API of Cache Operations scoped to one session. Keep values small and plain: under JSON serialization a User model came back on the next request as an array, and a Carbon 16,596 date as a string.