Skip to content

The Context

Architecture Concepts

The Context

Introduction

Every request and console command your application handles runs in its own context, a standard Go context.Context that holds your application along with the values that belong to that request or command. In a handler, the request r is that context.

Deep inside your application, a function often needs a configuration value, a route's URL, or a service. Instead of passing the application down to every function that might need it, give the function a ctx context.Context as its first parameter. Laravel's functions, such as config.From, urls.Route, and services.From, read what they need from that context.

For example, a method on your User model in models/user.go may build the user's profile URL without taking the application as an argument:

1package models
2 
3import (
4 "context"
5 
6 "go.laravel.com/urls"
7)
8 
9func (u *User) ProfileURL(ctx context.Context) (string, error) {
10 return urls.Route(ctx, "users.show", "user", u.ID)
11}
1package models
2 
3import (
4 "context"
5 
6 "go.laravel.com/urls"
7)
8 
9func (u *User) ProfileURL(ctx context.Context) (string, error) {
10 return urls.Route(ctx, "users.show", "user", u.ID)
11}

A handler calls user.ProfileURL(r), and code that runs outside a request passes the ctx it received. Since r is the same context that r.Context() returns, you may also pass r to any other Go library that takes a context, such as an HTTP client.

Where each context comes from

Laravel hands your code a context that carries the application wherever it runs that code. A handler and a middleware receive the request, r. A queued job, a listener, a command, and a scheduled task each receive a ctx of their own, and so do your tests, through client.Context(). A job, a command, or a scheduled task has no logged-in user, so give a job the user it acts for in a model field.

Declare your own functions' parameter as a context.Context, not a *web.Request. A function that takes a *web.Request can only run during a request, while a function that takes a context also runs from a job, a command, or a test. Everything else about a request stays on the request itself, such as its input, its session, and its route, so read the values you need in the handler and pass them on as arguments.

If you pass a context that doesn't carry the application, such as context.Background() or t.Context(), Laravel's functions panic with a message that names the function and says which context to pass instead:

1urls.Route needs the application's context, but ctx doesn't carry it: pass the request, the ctx that your job, listener, or command received, or client.Context() in a test, not context.Background() or t.Context()
1urls.Route needs the application's context, but ctx doesn't carry it: pass the request, the ctx that your job, listener, or command received, or client.Context() in a test, not context.Background() or t.Context()

In code that holds the application but runs outside all of these places, such as a main function of your own, app.Context(ctx) returns a context that carries the application.

Adding to the context

When you're reading logs, you often want to know which tenant or user a line came from. The log package adds values like these to the context, and every line you log with that context carries them, so you can find every line a tenant's request logged. A middleware is a good place to add them:

1package tenants
2 
3import (
4 "strings"
5 
6 "go.laravel.com/log"
7 "go.laravel.com/web"
8)
9 
10func Identify(r *web.Request, next web.Next) *web.Response {
11 // acme.example.com is the acme tenant...
12 tenant, _, _ := strings.Cut(r.Host, ".")
13 
14 return next(r.WithContext(log.With(r, "tenant", tenant)))
15}
1package tenants
2 
3import (
4 "strings"
5 
6 "go.laravel.com/log"
7 "go.laravel.com/web"
8)
9 
10func Identify(r *web.Request, next web.Next) *web.Response {
11 // acme.example.com is the acme tenant...
12 tenant, _, _ := strings.Cut(r.Host, ".")
13 
14 return next(r.WithContext(log.With(r, "tenant", tenant)))
15}

Like context.WithValue, log.With returns a new context rather than changing the one you pass it, so the Identify middleware passes the request on with r.WithContext. Adding a key again replaces its value. Log with one of slog's context functions, such as slog.InfoContext, so the line carries the log values, along with the request's ID that Laravel adds for you:

1slog.InfoContext(ctx, "Order placed.", "order", order.ID)
1slog.InfoContext(ctx, "Order placed.", "order", order.ID)

Any code that runs later in the request may read a value back with log.Value, which reports whether the context carries the key. You may remove a key with log.Without, which returns a new context too:

1if tenant, ok := log.Value(ctx, "tenant"); ok {
2 slog.InfoContext(ctx, "Tenant found.", "slug", tenant.String())
3}
1if tenant, ok := log.Value(ctx, "tenant"); ok {
2 slog.InfoContext(ctx, "Tenant found.", "slug", tenant.String())
3}

A queued job starts with the log values of the context that dispatched it, so the job's log lines carry the same tenant as the request. When the request reports a server error, the report carries the log values too, and your report hook may read them with log.Attrs(r), such as to tag the error in your error tracker. To see how log values look in your log files, check out the logging guide's section on adding context.

Hidden values

Sometimes a queued job needs a value that shouldn't appear in your logs, such as the ID of an admin who is acting as another user. Add it with log.WithHidden, which the context's jobs carry but its log lines don't show. Read the value back with log.Hidden, which returns it as the type you name, and remove it with log.WithoutHidden:

1ctx = log.WithHidden(ctx, "impersonator", admin.ID)
2 
3impersonator, ok := log.Hidden[int64](ctx, "impersonator")
1ctx = log.WithHidden(ctx, "impersonator", admin.ID)
2 
3impersonator, ok := log.Hidden[int64](ctx, "impersonator")

A job receives hidden values as JSON, so name a type that the value's JSON decodes into, such as int64 for an ID.

Adding values of your own

For a value that only code in the same request needs, such as the team that a subdomain names, add it to the context with context.WithValue instead. Keep the context key private to one package, and give that package a function that reads the value, so no other package can overwrite the value or read it as the wrong type. For example, this teams package loads the team in its Resolve middleware, and returns it from FromContext:

1package teams
2 
3import (
4 "context"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type contextKey struct{}
13 
14func Resolve(r *web.Request, next web.Next) *web.Response {
15 team, err := model.Query[models.Team]().
16 WhereEq("slug", r.PathValue("team")).
17 First(r)
18 if err != nil {
19 return web.Fail(err)
20 }
21 
22 ctx := context.WithValue(r.Context(), contextKey{}, team)
23 
24 return next(r.WithContext(ctx))
25}
26 
27func FromContext(ctx context.Context) (models.Team, bool) {
28 team, ok := ctx.Value(contextKey{}).(models.Team)
29 
30 return team, ok
31}
1package teams
2 
3import (
4 "context"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type contextKey struct{}
13 
14func Resolve(r *web.Request, next web.Next) *web.Response {
15 team, err := model.Query[models.Team]().
16 WhereEq("slug", r.PathValue("team")).
17 First(r)
18 if err != nil {
19 return web.Fail(err)
20 }
21 
22 ctx := context.WithValue(r.Context(), contextKey{}, team)
23 
24 return next(r.WithContext(ctx))
25}
26 
27func FromContext(ctx context.Context) (models.Team, bool) {
28 team, ok := ctx.Value(contextKey{}).(models.Team)
29 
30 return team, ok
31}

A handler behind the Resolve middleware calls teams.FromContext(r), and so does any function the handler passes its context to. Use the context only for values that describe the whole request, such as the team. When only one function needs a value, pass the value as an argument, since a function's signature can't show what the function reads from the context.

Memoizing with Once

Sometimes several parts of a request need the same value, such as a count of users that both the handler and a shared Inertia prop show. Rather than query it twice, wrap the function that loads the value with laravel.Once. The function runs once per request, and later calls in the same request get the first call's result. Declare the wrapped function as a package variable, such as in models/user.go, next to your User model:

1package models
2 
3import (
4 "context"
5 
6 laravel "go.laravel.com"
7 "go.laravel.com/model"
8)
9 
10var UserCount = laravel.Once(func(ctx context.Context) (int, error) {
11 return model.Query[User]().Count(ctx)
12})
1package models
2 
3import (
4 "context"
5 
6 laravel "go.laravel.com"
7 "go.laravel.com/model"
8)
9 
10var UserCount = laravel.Once(func(ctx context.Context) (int, error) {
11 return model.Query[User]().Count(ctx)
12})

A handler calls models.UserCount(r). The function runs once even when several goroutines ask at the same time. The result is only remembered for the current request, so the next request runs the function again, and each job attempt, command, and run of a scheduled task remembers results of its own. Once remembers an error like any other result, so a failed query isn't run again until the next request. A call that panics, or that fails because its context ended, isn't remembered.

Every caller gets the same result, so when the function returns a pointer, a slice, or a map, every caller shares what it points to. Don't change that value in one caller, or copy it before you change it.

Keyed values

When the function takes an argument, such as a user's ID, use laravel.OnceFor, which remembers a separate result for each argument. Calling models.FindUser(r, 1) twice in a request queries the database once, while models.FindUser(r, 2) runs its own query and remembers its own result:

1var FindUser = laravel.OnceFor(func(ctx context.Context, id int64) (User, error) {
2 return model.Find[User](ctx, id)
3})
1var FindUser = laravel.OnceFor(func(ctx context.Context, id int64) (User, error) {
2 return model.Find[User](ctx, id)
3})

The argument must be a value Go can compare with ==, such as an int64 ID or a string. For example, pass user.ID rather than a whole User.

When a request ends

A request's context carries one more thing: whether anybody still needs the request's work. Laravel cancels the context when the visitor leaves, such as by closing the page, when the route's timeout passes, when the server is shutting down and the request is still running at the deadline, and once Laravel has sent the response. For a timeout or a shutdown, Laravel answers the visitor with a 503.

Go can't stop a running function from outside, so canceling the context doesn't end your handler. Instead, it ends the work that watches the context. A query that received r returns an error within moments, your handler fails with that error, and Laravel answers without reporting it, because the handler did nothing wrong. So a handler that passes r to every query and HTTP call needs no other code to handle timeouts and shutdown.

A loop that only computes, without waiting on a query or a call, never sees the cancellation. If the loop runs long, check the context yourself on each pass:

1for _, row := range rows {
2 if err := r.Err(); err != nil {
3 return web.Fail(err)
4 }
5 
6 total += score(row)
7}
1for _, row := range rows {
2 if err := r.Err(); err != nil {
3 return web.Fail(err)
4 }
5 
6 total += score(row)
7}

Running work after the response

Some cleanup shouldn't make the visitor wait, such as removing a temporary file that a download sent. Register the cleanup with r.OnFinish, and Laravel runs it once the response has been sent, whether the request succeeded or failed:

1package reports
2 
3import (
4 "os"
5 
6 "go.laravel.com/web"
7)
8 
9func Download(r *web.Request) *web.Response {
10 path, err := build(r, r.PathValue("report"))
11 if err != nil {
12 return web.Fail(err)
13 }
14 
15 r.OnFinish(func() { os.Remove(path) })
16 
17 return web.Download(path, "report.pdf")
18}
1package reports
2 
3import (
4 "os"
5 
6 "go.laravel.com/web"
7)
8 
9func Download(r *web.Request) *web.Response {
10 path, err := build(r, r.PathValue("report"))
11 if err != nil {
12 return web.Fail(err)
13 }
14 
15 r.OnFinish(func() { os.Remove(path) })
16 
17 return web.Download(path, "report.pdf")
18}

Here build stands for a function of your own that writes the report and returns its path. The request's context has ended by the time your OnFinish functions run, and the connection stays busy until they return, so keep OnFinish for quick cleanup like this, and run anything slower as background work.

Background work

A goroutine you start with go gets only the context you pass it. If you pass r, the goroutine's queries fail as soon as the response is sent, because the request's context has ended by then, and a panic in the goroutine ends your whole application. To run work that doesn't need to hold up the response, such as telling a webhook that an order shipped, start it with r.Background instead, and the handler returns without waiting for it:

1package orders
2 
3import (
4 "context"
5 
6 "go.laravel.com/web"
7 
8 "app/store"
9 "app/webhooks"
10)
11 
12func Ship(r *web.Request) *web.Response {
13 order, err := store.ShipOrder(r, r.PathValue("order"))
14 if err != nil {
15 return web.Fail(err)
16 }
17 
18 r.Background(func(ctx context.Context) error {
19 return webhooks.OrderShipped(ctx, order.ID)
20 })
21 
22 return web.Back()
23}
1package orders
2 
3import (
4 "context"
5 
6 "go.laravel.com/web"
7 
8 "app/store"
9 "app/webhooks"
10)
11 
12func Ship(r *web.Request) *web.Response {
13 order, err := store.ShipOrder(r, r.PathValue("order"))
14 if err != nil {
15 return web.Fail(err)
16 }
17 
18 r.Background(func(ctx context.Context) error {
19 return webhooks.OrderShipped(ctx, order.ID)
20 })
21 
22 return web.Back()
23}

Here app/store and app/webhooks stand for code of your own. The work's ctx carries the application and the values you've added, and it shares the request's Once results, but it doesn't end when the response is sent, so pass that ctx to the work, not r. If you start the work inside a transaction, it starts once the transaction commits, and a rollback discards it. Read what the work needs from the request before you start it, as the handler loads order here, because Laravel closes the request's body and removes its uploaded files once the handler returns.

When the work returns an error or panics, Laravel reports it, as it reports a handler's. When the server shuts down, it waits for background work, up to SERVER_SHUTDOWN_TIMEOUT. In your tests, a request returns only once the background work it started has finished, so your assertions see what the work did.

Code that has a ctx rather than a request, such as a command, a job, or a scheduled task, starts background work with laravel.Background. A command waits for the background work it started before the process exits:

1laravel.Background(ctx, func(ctx context.Context) error {
2 return webhooks.PostPublished(ctx, post.ID)
3})
1laravel.Background(ctx, func(ctx context.Context) error {
2 return webhooks.PostPublished(ctx, post.ID)
3})

When you need the work's result later in the same handler, or want to run several operations at once, check out the concurrency and tasks guide.

Background work isn't a queue. Nothing retries it, and a crash or a deploy that outlasts the shutdown timeout loses it. For work that must happen, such as charging a card or sending a receipt, dispatch a queued job instead.