Skip to content

Session

The Basics

Sessions

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 before your handler runs and saves it afterward. Because the web middleware group includes StartSession, every route in routes/web.go automatically has access to the session. Routes in the api group 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 laravel_session
SESSION_DOMAIN The cookie's Domain none
SESSION_SECURE_COOKIE Whether the cookie is sent only over HTTPS when the request arrived over 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, generate a migration, which make:migration also adds to the All list in database/migrations/migrations.go:

1laravel make:migration create_sessions_table
1laravel make:migration create_sessions_table

Then call session.CreateTable(ctx) in the migration to create the sessions table with the columns the database driver expects:

1// database/migrations/2026_01_01_000000_create_sessions_table.go
2package migrations
3 
4import (
5 "context"
6 
7 "go.laravel.com/session"
8)
9 
10func createSessionsTable(ctx context.Context) error {
11 return session.CreateTable(ctx)
12}
1// database/migrations/2026_01_01_000000_create_sessions_table.go
2package migrations
3 
4import (
5 "context"
6 
7 "go.laravel.com/session"
8)
9 
10func createSessionsTable(ctx context.Context) error {
11 return session.CreateTable(ctx)
12}

If your users use UUIDs as primary keys, create the table with schema.Create and define user_id with table.UUID("user_id") instead. 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 cfg.Session.Lottery in your options' Configure function in bootstrap/app.go:

1import (
2 "go.laravel.com/config"
3 "go.laravel.com/lottery"
4)
5 
6func configure(cfg *config.Config, env *config.Env) {
7 cfg.Session.Lottery = lottery.Odds(1, 50)
8}
1import (
2 "go.laravel.com/config"
3 "go.laravel.com/lottery"
4)
5 
6func configure(cfg *config.Config, env *config.Env) {
7 cfg.Session.Lottery = lottery.Odds(1, 50)
8}

Redis sessions

To store sessions in Redis, select the redis driver in your .env file:

1SESSION_DRIVER=redis
1SESSION_DRIVER=redis

The driver uses your default Redis connection, which reads REDIS_URL, 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, call r.Session() on the request:

1package settings
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 theme, ok := r.Session().Value[string]("theme")
11 if !ok {
12 theme = "light"
13 }
14 
15 return web.Text(fmt.Sprintf("You're using the %s theme", theme))
16}
1package settings
2 
3import (
4 "fmt"
5 
6 "go.laravel.com/web"
7)
8 
9func Show(r *web.Request) *web.Response {
10 theme, ok := r.Session().Value[string]("theme")
11 if !ok {
12 theme = "light"
13 }
14 
15 return web.Text(fmt.Sprintf("You're using the %s theme", theme))
16}

Route middleware may call r.Session() as well. Calling r.Session() on a route that doesn't run StartSession, such as an api route, panics, and the request fails with a server error. If your middleware runs on routes that might not have a session, check r.HasSession() first.

Laravel saves the session after your handler returns and before it sends the response. If you return a streamed response, make any session changes in the handler before returning web.Stream, because Laravel calls the stream's function after the session is saved.

Retrieving data

The Value method retrieves an item from the session and converts it into the type you name in brackets. Its second result is false if the key is missing or if the stored value can't become the requested type. You may use "dot" notation to read nested values:

1theme, ok := r.Session().Value[string]("settings.theme")
2 
3locale, ok := r.Session().Value[string]("settings.locale")
4if !ok {
5 locale = "en"
6}
1theme, ok := r.Session().Value[string]("settings.theme")
2 
3locale, ok := r.Session().Value[string]("settings.locale")
4if !ok {
5 locale = "en"
6}

The session stores its data as JSON, so Value is the method to reach for when you need a specific type. The Get method returns the item as JSON decoded it, or nil when it's missing, so a number you stored as an int comes back from Get as a float64, and a struct comes back as a map[string]any:

1status := r.Session().Get("status")
1status := r.Session().Get("status")

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

1if r.Session().Has("settings") {
2 // ...
3}
4 
5if r.Session().Exists("settings") {
6 // ...
7}
1if r.Session().Has("settings") {
2 // ...
3}
4 
5if r.Session().Exists("settings") {
6 // ...
7}

To retrieve a typed item and remove it from the session in one step, use Pull. Like Value, it converts the stored value into the type you name in brackets and returns false if the key is missing or doesn't fit. To retrieve a copy of every item in the session as a map, use All:

1coupon, ok := r.Session().Pull[string]("coupon")
2 
3data := r.Session().All()
1coupon, ok := r.Session().Pull[string]("coupon")
2 
3data := r.Session().All()

Storing data

To store an item in the session, call Put with a key and any value that JSON can encode, such as a string, a number, a slice, a map, or a struct with exported fields:

1r.Session().Put("theme", "dark")
1r.Session().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 with Value:

1type Settings struct {
2 Theme string `json:"theme"`
3 Locale string `json:"locale"`
4}
5 
6r.Session().Put("settings.theme", "dark")
7r.Session().Put("settings.locale", "fr")
8 
9settings, ok := r.Session().Value[Settings]("settings")
1type Settings struct {
2 Theme string `json:"theme"`
3 Locale string `json:"locale"`
4}
5 
6r.Session().Put("settings.theme", "dark")
7r.Session().Put("settings.locale", "fr")
8 
9settings, ok := r.Session().Value[Settings]("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:

1package posts
2 
3import "go.laravel.com/web"
4 
5func Store(r *web.Request) *web.Response {
6 // Create the post...
7 
8 r.Session().Flash("status", "Post published!")
9 
10 return web.Redirect("/posts")
11}
1package posts
2 
3import "go.laravel.com/web"
4 
5func Store(r *web.Request) *web.Response {
6 // Create the post...
7 
8 r.Session().Flash("status", "Post published!")
9 
10 return web.Redirect("/posts")
11}

On the next request, read the flashed value with r.Session().Value[string]("status"). You may also flash data directly on a redirect with With:

1return web.Redirect("/posts").With("status", "Post published!")
1return web.Redirect("/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:

1r.Session().Reflash()
2r.Session().Keep("status", "error")
1r.Session().Reflash()
2r.Session().Keep("status", "error")

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

1r.Session().Now("status", "Post published!")
1r.Session().Now("status", "Post published!")

Deleting data

To remove items from the session, pass their keys to 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:

1r.Session().Forget("coupon")
2 
3r.Session().Flush()
1r.Session().Forget("coupon")
2 
3r.Session().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:

1r.Session().Regenerate()
1r.Session().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:

1r.Session().Invalidate()
1r.Session().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 session.Store interface:

1package sessions
2 
3import (
4 "context"
5 "time"
6 
7 "go.laravel.com/session"
8)
9 
10type MemcachedStore struct {
11 Addr string
12 Lifetime time.Duration
13 // Your Memcached client...
14}
15 
16func (s *MemcachedStore) Read(ctx context.Context, id string) ([]byte, error) {
17 // Return the payload stored under the ID...
18 return nil, nil
19}
20 
21func (s *MemcachedStore) Write(
22 ctx context.Context,
23 id string,
24 payload []byte,
25 write session.Write,
26) error {
27 // Store the payload under the ID, and expire it after the lifetime...
28 return nil
29}
30 
31func (s *MemcachedStore) Destroy(ctx context.Context, id string) error {
32 // Delete the payload stored under the ID...
33 return nil
34}
1package sessions
2 
3import (
4 "context"
5 "time"
6 
7 "go.laravel.com/session"
8)
9 
10type MemcachedStore struct {
11 Addr string
12 Lifetime time.Duration
13 // Your Memcached client...
14}
15 
16func (s *MemcachedStore) Read(ctx context.Context, id string) ([]byte, error) {
17 // Return the payload stored under the ID...
18 return nil, nil
19}
20 
21func (s *MemcachedStore) Write(
22 ctx context.Context,
23 id string,
24 payload []byte,
25 write session.Write,
26) error {
27 // Store the payload under the ID, and expire it after the lifetime...
28 return nil
29}
30 
31func (s *MemcachedStore) Destroy(ctx context.Context, id string) error {
32 // Delete the payload stored under the ID...
33 return nil
34}

Laravel encodes the session for you, and encrypts it when SESSION_ENCRYPT is true, so your store saves each payload and returns it unchanged:

  • Read returns the payload stored under the ID, or nil and no error when no session exists or when the session has been idle longer than its lifetime.
  • Write stores the payload. When write.Existing is true, update the record only if the session still exists so a session destroyed by a logout while the request ran stays destroyed. write also 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.

Each method receives the request's context, so your store may reach a client in your services with services.From(ctx).

Two additional interfaces are optional. Implement session.GarbageCollector to delete expired sessions when your backend doesn't expire keys automatically, and implement session.UserSessions 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 under a name in your options' Register function in bootstrap/app.go, then select it with SESSION_DRIVER=memcached:

1Register: func(app *laravel.Registrar) error {
2 app.SessionStore("memcached", &sessions.MemcachedStore{
3 Addr: app.Env().String("MEMCACHED_ADDR", "127.0.0.1:11211"),
4 Lifetime: 2 * time.Hour,
5 })
6 
7 return nil
8},
1Register: func(app *laravel.Registrar) error {
2 app.SessionStore("memcached", &sessions.MemcachedStore{
3 Addr: app.Env().String("MEMCACHED_ADDR", "127.0.0.1:11211"),
4 Lifetime: 2 * time.Hour,
5 })
6 
7 return nil
8},

Because SESSION_DRIVER chooses the store, your tests stay on the memory driver they select for you. A package registers a custom driver the same way with app.SessionStore("memcached", store) inside its Register method. To learn more, check out the packages guide's section on what a package can add.

Testing

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

1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "app/tests"
8)
9 
10func TestPlacingAnOrderUsesTheCoupon(t *testing.T) {
11 client := tests.New(t)
12 
13 client.WithSession(map[string]any{"coupon": "WELCOME10"}).
14 Post("/orders", url.Values{"product": {"42"}}).
15 AssertSessionHas("status", "Order placed!").
16 AssertSessionMissing("coupon")
17}
1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "app/tests"
8)
9 
10func TestPlacingAnOrderUsesTheCoupon(t *testing.T) {
11 client := tests.New(t)
12 
13 client.WithSession(map[string]any{"coupon": "WELCOME10"}).
14 Post("/orders", url.Values{"product": {"42"}}).
15 AssertSessionHas("status", "Order placed!").
16 AssertSessionMissing("coupon")
17}

To verify only that a key exists in the session without asserting its exact value, use AssertSessionPresent. To learn more about carrying a session across multiple requests or following a second browser, check out the testing guide's section on cookies and sessions.