Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 67 ยท Validation, Sessions and Files

Sessions, Flash Data and Cookies

Learn how Laravel sessions work, how to store and read data, flash messages and old input, regenerate session IDs, and how encrypted cookies are protected.

HTTP forgets everything between requests. Yet a shopping cart, a "Profile saved" banner and a logged-in user all need memory. Laravel gives you that memory through the session: a small bag of data kept on the server, found again on each request through a random ID stored in a cookie. If you have read PHP sessions, the idea is the same, but Laravel replaces $_SESSION with a clean API, pluggable storage and flash data that lives for exactly one more request.

This lesson covers where sessions are stored, how to read and write them, how flash messages and old form input work, why you regenerate the session ID, and how cookies are protected. Validation errors are carried to the next page the same way, which is why validation and sessions are taught side by side.

How a session travels

Laravel's StartSession middleware runs on every web route. It reads the session cookie, loads the matching session from the configured driver, lets your code use it, and saves it again when the response is ready. The browser only ever holds the ID, never the data.

sequenceDiagram
    participant B as Browser
    participant L as Laravel
    participant S as Session store
    B->>L: GET /cart (cookie: session ID)
    L->>S: load data for that ID
    S-->>L: cart items, flash data
    L-->>B: response (Set-Cookie: session ID)
    L->>S: save updated data

The cookie carries only an ID; the data stays in the store you configured.

Choosing a session driver

The driver is set in .env and read by config/session.php:

INI
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false

The common drivers are:

Driver Where the data lives Good for
file Files in storage/framework/sessions A single server
database A sessions table The default for a new project, easy to inspect
redis / memcached An in-memory server Fast, shared between servers
cookie Inside the encrypted cookie itself Tiny sessions, no server storage
array PHP memory for one request Tests; nothing is saved

SESSION_LIFETIME is in minutes of inactivity. With SESSION_ENCRYPT=true the stored payload is encrypted too, which helps if someone can read your session table or files. The database driver needs the sessions table, which a fresh project's migrations already create (see migrations).

Reading and writing session data

You can reach the session through the request, the session() helper or the Session facade. They all talk to the same store.

PHP
use Illuminate\Http\Request;

Route::post('/cart/add', function (Request $request) {
    // Write
    $request->session()->put('cart.items.42', 1);

    // Read, with a default if the key is missing
    $items = $request->session()->get('cart.items', []);

    // The same through the helper
    session(['last_seen' => 'products']);
    $page = session('last_seen');

    return back();
});

Keys use dot notation for nested arrays. The methods you will use most:

  • put($key, $value) stores a value; push('cart.items', $x) appends to an array inside it.
  • get($key, $default) reads; pull($key) reads and deletes in one step.
  • has($key) is true when the key exists and is not null; exists($key) is true even for null; missing($key) is the opposite of exists.
  • forget($key) removes one or more keys; flush() removes everything.
  • increment($key) and decrement($key) change a counter.

Keep sessions small. Store IDs and flags, not whole Eloquent models: the data is serialized on every request and may be stale by the time you read it.

Here is a stand-in that behaves like the core of the session: a nested array with dot-notation access.

PHP A session bag with dot notation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real session uses the same dot-notation idea (through Arr::get and Arr::set), which is why session('cart.items.42') works.

Flash data: remembered for one more request

Some data should survive exactly one redirect, such as "Post published". That is flash data:

PHP
Route::post('/posts', function () {
    // ...save the post...
    return redirect('/posts')->with('status', 'Post published!');
});

with() on a redirect calls session()->flash() for you. In the next request you read it like any other key, and then it is gone:

BLADE
@if (session('status'))
    <div class="alert">{{ session('status') }}</div>
@endif

Under the hood, flashed keys are listed in two internal arrays, _flash.new and _flash.old. When a request finishes, the session ages its flash data: everything in old is deleted, and everything in new moves to old. So data flashed in request 1 is readable in request 2 and removed when request 2 ends.

Related helpers:

  • flash($key, $value) stores a value for the next request.
  • now($key, $value) makes a value available only for the current request.
  • reflash() keeps all flash data for one more request, and keep(['status']) keeps only the named keys. Use them when a redirect chain passes through an extra hop.
flowchart LR
    A["Request 1<br/>flash('status')"] -->|"key moves to _flash.old"| B["Request 2<br/>reads status"]
    B -->|"key deleted at the end"| C["Request 3<br/>status is gone"]

Flash data lives through one more request, then disappears.

The next stand-in reproduces that aging step so you can watch it happen, including keep().

PHP Flash data lifecycle across requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Old input and validation errors

When validation fails, Laravel redirects back to the form and flashes two things: the errors (under the errors key, shown with $errors or @error) and the submitted input. You can flash input yourself:

PHP
return back()->withInput()->withErrors(['email' => 'We could not find that address.']);

In a Blade template, old('email') reads the flashed input so the field is refilled. Laravel never flashes fields named password, password_confirmation or current_password; you can extend that list in the exception handler configuration (see logging and errors). The form side of this is covered in forms, CSRF and assets.

Regenerating and invalidating the session

A session ID is a password for that browser. If an attacker plants a known ID on a victim and the victim then logs in, the attacker holds a logged-in session: this is session fixation. The defense is to issue a new ID at the moment privileges change:

PHP
$request->session()->regenerate();   // new ID, same data (after login)
$request->session()->invalidate();   // delete data and issue a new ID (logout)
$request->session()->regenerateToken(); // new CSRF token too

Laravel's authentication code does this for you in Auth::attempt flows, but call it yourself if you build a custom login. The reasoning is the same as session_regenerate_id(true) in plain PHP.

Cookies and encryption

Cookies are small values the browser sends with every request. You will rarely set them by hand, but when you do:

PHP
use Illuminate\Support\Facades\Cookie;

return response('ok')->cookie('theme', 'dark', 60 * 24 * 30); // minutes

Cookie::queue('theme', 'dark', 60 * 24 * 30); // attach to the outgoing response

$theme = $request->cookie('theme', 'light');

The EncryptCookies middleware encrypts every cookie your app sets and decrypts every incoming one. The value is encrypted with your APP_KEY and carries an authentication code, so the browser can neither read it nor change it: a tampered cookie fails to decrypt and is treated as missing. That is why rotating APP_KEY logs everyone out.

Some cookies must stay readable by JavaScript or by another system. Opt out explicitly in bootstrap/app.php:

PHP
->withMiddleware(function (Middleware $middleware) {
    $middleware->encryptCookies(except: ['signed_in']);
})

This very site does exactly that for a harmless signed_in hint cookie. Never exclude a cookie that carries anything sensitive.

Cookie behavior is tuned in config/session.php: http_only (hide the cookie from JavaScript), secure (HTTPS only, set SESSION_SECURE_COOKIE=true in production) and same_site (lax by default, a basic CSRF defense).

The stand-in below does not encrypt; it only signs a value with a secret, which shows the tamper-detection half of the idea.

PHP Detecting a tampered cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real Laravel cookies are encrypted (AES-256 with an authentication code), not just signed, so their contents are hidden as well as protected. The stand-in keeps the demo short and deterministic.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A controller runs return redirect('/posts')->with('status', 'Saved'). When is session('status') still available?

    with() flashes the value. At the end of the next request Laravel ages the flash data and deletes it, unless you call reflash() or keep().
  2. 2. Why should you call $request->session()->regenerate() after a successful login?

    An attacker may have planted a known session ID before login. A fresh ID invalidates it while keeping the data.
  3. 3. What does the EncryptCookies middleware do to a cookie that the user edited in dev tools?

    The encrypted value carries an authentication code. Any change breaks it, so the cookie is rejected.
  4. 4. Which session driver stores nothing on the server?

    The cookie driver keeps the whole session inside the encrypted cookie. The other three store the data server-side and only send an ID.

Summary

  • A Laravel session is server-side data found through an ID in a cookie. StartSession loads and saves it on every web request.
  • Choose the store with SESSION_DRIVER (database, file, redis, cookie, array); SESSION_LIFETIME counts idle minutes.
  • Use put, get, has, pull, forget, push and increment, with dot notation for nested keys. Keep sessions small.
  • Flash data (with(), flash()) survives one more request; reflash() and keep() extend it, and now() limits it to the current request.
  • Validation failures flash errors and old input, which @error and old() read; password fields are never flashed.
  • Regenerate the session ID when privileges change (login) and invalidate it on logout.
  • EncryptCookies encrypts and authenticates cookies with APP_KEY; exclude a cookie only when it must be readable and carries nothing sensitive.

Next: File Uploads and the Storage System