Skip to content

Session

The Basics

Session

Introduction

Since HTTP is stateless, sessions provide a way to store information about a user across multiple requests. For example, sessions keep track of who is logged in, store the color theme a user selected, or carry a status message across a redirect.

Laravel's StartSession middleware loads the session at the beginning of each request and saves it when the response is sent. Because the web middleware group includes StartSession, every route in src/routes/web.rs automatically has access to the session. Routes in src/routes/api.rs are stateless and don't start a session.

Configuration

The SESSION_DRIVER environment variable configures where Laravel stores session data. New applications use the database driver, which is the right choice for most applications because every server shares the same sessions and sessions survive deploys.

Laravel includes several built-in session drivers:

  • database stores sessions in a table in your database.
  • redis stores sessions in Redis / Valkey.
  • file stores sessions on disk in storage/framework/sessions.
  • cookie stores the session in an encrypted cookie, requiring no server-side storage. It's the default when SESSION_DRIVER isn't set.
  • memory stores sessions in memory and clears them when the server restarts, making it ideal for tests.

Sessions expire after SESSION_LIFETIME minutes of inactivity (120 minutes by default). The cookie driver always encrypts session data. To encrypt session data stored by the other drivers as well, set SESSION_ENCRYPT=true:

1SESSION_DRIVER=database
2SESSION_LIFETIME=120
3SESSION_ENCRYPT=false
1SESSION_DRIVER=database
2SESSION_LIFETIME=120
3SESSION_ENCRYPT=false

You may customize the session cookie itself using these environment variables, though the defaults work well for most applications:

Variable Sets Default
SESSION_COOKIE The cookie's name the app's name, as my_app_session
SESSION_DOMAIN The cookie's Domain none
SESSION_SECURE_COOKIE Whether the cookie is sent only over HTTPS when APP_URL is https
SESSION_SAME_SITE The cookie's SameSite lax
SESSION_EXPIRE_ON_CLOSE Whether the session ends when the browser closes false

The cookie driver works well as long as your sessions stay small. Browsers ignore cookies larger than 4 KB, and that limit includes any old input and validation errors flashed after a failed form submission, so a single long text field can overflow the cookie. In debug mode and in tests, a session that exceeds the cookie size limit fails the request. If you run into this limit, store less in the session or switch to the database or redis driver.

The database session table

The database driver stores sessions in a sessions table. New applications include this table in their initial migration alongside the users table. If your application doesn't have it yet, add a migration that holds only the session::table! macro, which creates the table:

1// database/migrations/2026_01_01_000000_create_sessions_table.rs
2laravel::session::table!();
1// database/migrations/2026_01_01_000000_create_sessions_table.rs
2laravel::session::table!();

If you'd like to change the table, such as storing UUIDs in user_id because your users use UUIDs as primary keys, replace the macro with the migration it stands for and edit it. For UUIDs, define user_id with table.uuid("user_id"):

1// database/migrations/2026_01_01_000000_create_sessions_table.rs
2use laravel::db::AnyTransaction;
3 
4pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
5 tx.schema()
6 .create("sessions", |table| {
7 table.string("id").primary();
8 table.big_integer("user_id").nullable().index();
9 table.string("ip_address").length(45).nullable();
10 table.text("user_agent").nullable();
11 table.long_text("payload");
12 table.timestamp("last_activity").index();
13 })
14 .await
15}
1// database/migrations/2026_01_01_000000_create_sessions_table.rs
2use laravel::db::AnyTransaction;
3 
4pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
5 tx.schema()
6 .create("sessions", |table| {
7 table.string("id").primary();
8 table.big_integer("user_id").nullable().index();
9 table.string("ip_address").length(45).nullable();
10 table.text("user_agent").nullable();
11 table.long_text("payload");
12 table.timestamp("last_activity").index();
13 })
14 .await
15}

Each row records the signed-in user's ID, IP address, and user agent from the session's most recent request, which makes it possible to display a list of active devices to your users.

By default, the database driver uses your default database connection and a table named sessions. To use a different connection or table name, set SESSION_CONNECTION or SESSION_TABLE.

You don't need to schedule a cleanup job, because Laravel automatically deletes expired rows on 2 out of every 100 requests using a lottery. To customize these cleanup odds, set the lottery field in src/config/session.rs:

1// src/config/session.rs
2use laravel::config::session::Session;
3use laravel::config::{self, Env};
4use laravel::lottery::Lottery;
5 
6#[config::section]
7fn session(env: &Env) -> Session {
8 Session {
9 lottery: Lottery::odds(1, 50),
10 ..Session::from_env(env)
11 }
12}
1// src/config/session.rs
2use laravel::config::session::Session;
3use laravel::config::{self, Env};
4use laravel::lottery::Lottery;
5 
6#[config::section]
7fn session(env: &Env) -> Session {
8 Session {
9 lottery: Lottery::odds(1, 50),
10 ..Session::from_env(env)
11 }
12}

Redis sessions

To store sessions in Redis, add Laravel's redis Cargo feature to laravel-rust in your Cargo.toml:

1[dependencies]
2laravel-rust = { version = "0.1", features = ["database-postgres", "redis"] }
1[dependencies]
2laravel-rust = { version = "0.1", features = ["database-postgres", "redis"] }

Then select the redis driver in your .env file:

1SESSION_DRIVER=redis
1SESSION_DRIVER=redis

The driver uses your default Redis connection, or the connection named by SESSION_CONNECTION. Redis expires idle sessions automatically, and sessions use a separate Redis database from your cache by default so clearing your cache doesn't sign users out.

Interacting with the session

To read or write session data in a handler, take a Session argument. Session is included in the prelude:

1use laravel::prelude::*;
2 
3pub async fn show(session: Session) -> String {
4 let theme: Option<String> = session.get("theme");
5 
6 format!("You're using the {} theme", theme.as_deref().unwrap_or("light"))
7}
1use laravel::prelude::*;
2 
3pub async fn show(session: Session) -> String {
4 let theme: Option<String> = session.get("theme");
5 
6 format!("You're using the {} theme", theme.as_deref().unwrap_or("light"))
7}

Route middleware may take a Session argument as well. Taking Session on a route that doesn't run StartSession, such as an api route, fails the request with a server error. If your handler already takes a Request argument, or runs on a route that might not have a session, call request.session() instead, which returns a laravel::Result<&Session>.

Laravel saves the session after your handler returns and before it sends the response body. If you return a streamed response, make any session changes in the handler before returning the stream.

Retrieving data

The get method retrieves an item from the session and deserializes it into the type you ask for. It returns None if the key is missing or if the stored value doesn't match the requested type. You may use "dot" notation to read nested values:

1let theme: Option<String> = session.get("settings.theme");
2 
3let locale: String = session.get("settings.locale").unwrap_or_else(|| "en".to_owned());
1let theme: Option<String> = session.get("settings.theme");
2 
3let locale: String = session.get("settings.locale").unwrap_or_else(|| "en".to_owned());

To check whether an item is present and not null, use has. To check whether a key exists even if its value is null, use exists:

1if session.has("settings") {
2 // ...
3}
4 
5if session.exists("settings") {
6 // ...
7}
1if session.has("settings") {
2 // ...
3}
4 
5if session.exists("settings") {
6 // ...
7}

To retrieve an item and remove it from the session in one step, use pull. To retrieve every item in the session as a JSON map, use all:

1let coupon: Option<String> = session.pull("coupon");
2 
3let data = session.all();
1let coupon: Option<String> = session.pull("coupon");
2 
3let data = session.all();

Storing data

To store an item in the session, call put with a key and any value that implements Serialize:

1session.put("theme", "dark");
1session.put("theme", "dark");

You may also use "dot" notation to store nested values. Laravel creates the nested JSON object automatically, so you may later read it back into a struct (or a serde_json::Value) with session.get("settings"):

1#[derive(Deserialize)]
2pub struct Settings {
3 pub theme: String,
4 pub locale: String,
5}
6 
7session.put("settings.theme", "dark");
8session.put("settings.locale", "fr");
9 
10let settings: Option<Settings> = session.get("settings");
1#[derive(Deserialize)]
2pub struct Settings {
3 pub theme: String,
4 pub locale: String,
5}
6 
7session.put("settings.theme", "dark");
8session.put("settings.locale", "fr");
9 
10let settings: Option<Settings> = session.get("settings");

Flash data

Sometimes you only want to store an item in the session for the next request, such as a confirmation banner after a form submission. The flash method stores a value for the current request and the next request, after which Laravel deletes it:

1use laravel::prelude::*;
2 
3pub async fn store(session: Session) -> laravel::Result<Redirect> {
4 // Create the post...
5 
6 session.flash("status", "Post published!");
7 
8 Ok(Redirect::to("/posts"))
9}
1use laravel::prelude::*;
2 
3pub async fn store(session: Session) -> laravel::Result<Redirect> {
4 // Create the post...
5 
6 session.flash("status", "Post published!");
7 
8 Ok(Redirect::to("/posts"))
9}

On the next request, read the flashed value with session.get("status"). You may also flash data directly on a redirect with with:

1Ok(Redirect::to("/posts").with("status", "Post published!"))
1Ok(Redirect::to("/posts").with("status", "Post published!"))

If you need to keep flash data around for an additional request, call reflash to keep all flashed items, or keep to preserve only specific keys:

1session.reflash();
2session.keep(["status", "error"]);
1session.reflash();
2session.keep(["status", "error"]);

To flash an item for the current request only, use now:

1session.now("status", "Post published!");
1session.now("status", "Post published!");

Deleting data

To remove a single item from the session, call forget. To clear all data from the session at once, call flush. Calling flush preserves the session's CSRF token, so forms the user already has open can still be submitted:

1session.forget("coupon");
2 
3session.flush();
1session.forget("coupon");
2 
3session.flush();

Regenerating the session ID

Regenerating the session ID prevents attackers from exploiting a session fixation attack by planting a known session ID in a user's browser before they log in. Laravel's authentication regenerates the session ID automatically when a user logs in, but if you build a custom login flow, call regenerate. Your existing session data is preserved under the new ID:

1session.regenerate()?;
1session.regenerate()?;

When a user logs out, call invalidate to clear all session data and generate a new session ID in one step. If you're using Laravel's built-in authentication, auth.logout() already calls invalidate for you:

1session.invalidate()?;
1session.invalidate()?;

Both regenerate and invalidate also generate a new CSRF token. With a server-side driver such as database or redis, the old session ID stops working immediately. Because the cookie driver stores no state on the server, a copy of an old session cookie remains valid until it expires, so use a server-side driver when logging out must revoke the session everywhere.

Session stores of your own

If you need to store sessions in a backend that Laravel's built-in drivers don't cover, such as Memcached, implement the SessionStore trait:

1use std::time::Duration;
2 
3use laravel::session::{Identity, SessionStore, Write};
4 
5pub struct MemcachedStore {
6 // Your Memcached client...
7}
8 
9impl SessionStore for MemcachedStore {
10 async fn read(&self, id: &str, lifetime: Duration) -> laravel::Result<Option<String>> {
11 // Return the payload stored under the ID...
12 todo!()
13 }
14 
15 async fn write(
16 &self,
17 id: &str,
18 payload: String,
19 lifetime: Duration,
20 identity: &Identity,
21 write: Write,
22 ) -> laravel::Result<()> {
23 // Store the payload under the ID, and expire it after the lifetime...
24 todo!()
25 }
26 
27 async fn destroy(&self, id: &str) -> laravel::Result<()> {
28 // Delete the payload stored under the ID...
29 todo!()
30 }
31}
1use std::time::Duration;
2 
3use laravel::session::{Identity, SessionStore, Write};
4 
5pub struct MemcachedStore {
6 // Your Memcached client...
7}
8 
9impl SessionStore for MemcachedStore {
10 async fn read(&self, id: &str, lifetime: Duration) -> laravel::Result<Option<String>> {
11 // Return the payload stored under the ID...
12 todo!()
13 }
14 
15 async fn write(
16 &self,
17 id: &str,
18 payload: String,
19 lifetime: Duration,
20 identity: &Identity,
21 write: Write,
22 ) -> laravel::Result<()> {
23 // Store the payload under the ID, and expire it after the lifetime...
24 todo!()
25 }
26 
27 async fn destroy(&self, id: &str) -> laravel::Result<()> {
28 // Delete the payload stored under the ID...
29 todo!()
30 }
31}

Laravel serializes and encrypts the session for you, so your store saves each payload and returns it unchanged:

  • read returns the payload stored under the ID, or None when no session exists or when the session has been idle longer than lifetime.
  • write stores the payload. When write is Write::Existing, update the record only if the session still exists so a session destroyed by a logout while the request ran stays destroyed. identity holds the user's ID, IP address, and user agent for stores that record them.
  • destroy deletes a session, such as after its ID is regenerated or invalidated.

Two additional methods are optional. Implement collect_garbage to delete expired sessions when your backend doesn't expire keys automatically, and implement destroy_others to delete a user's other sessions when they change their password if your store can look up sessions by user ID.

Once you've implemented the store, register it as a driver in src/app.rs and select it with SESSION_DRIVER=memcached:

1use laravel::prelude::*;
2 
3Application::configure()
4 .with_services(|app| {
5 app.sessions().extend("memcached", |_app| async { Ok(MemcachedStore {}) });
6 })
1use laravel::prelude::*;
2 
3Application::configure()
4 .with_services(|app| {
5 app.sessions().extend("memcached", |_app| async { Ok(MemcachedStore {}) });
6 })

The factory receives the container, so it may resolve services such as a client registered as a singleton. A package may register a custom driver by calling app.sessions().extend(...) inside its service provider's register method.

Testing

Tests use the memory session driver by default. To seed a request with session data, call with_session. To assert what the request left in the session (including flash data), use assert_session_has and assert_session_missing:

1use laravel::testing::prelude::*;
2 
3#[laravel::test]
4async fn placing_an_order_uses_the_coupon(app: Application) {
5 app.post("/orders")
6 .with_session(json!({ "coupon": "WELCOME10" }))
7 .await
8 .assert_session_has("status", "Order placed!")
9 .assert_session_missing("coupon");
10}
1use laravel::testing::prelude::*;
2 
3#[laravel::test]
4async fn placing_an_order_uses_the_coupon(app: Application) {
5 app.post("/orders")
6 .with_session(json!({ "coupon": "WELCOME10" }))
7 .await
8 .assert_session_has("status", "Order placed!")
9 .assert_session_missing("coupon");
10}

To verify only that a key exists in the session without asserting its exact value, use assert_session_present. To learn more about inspecting session values with custom assertions or carrying a session across multiple requests, check out the testing guide's section on cookies and sessions.