Skip to content

The Context

Architecture Concepts

The Context

Introduction

Every request and console command your application handles runs in its own context, a Tokio task-local value that holds your application along with the values that belong to that request or command.

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, you may call helpers such as laravel::config, laravel::url::route, and laravel::resolve from any function, and they read what they need from the context.

For example, any function in your application may build a user's profile URL without taking the application as an argument:

1use crate::http::handlers::users;
2use crate::models::User;
3 
4pub fn profile_url(user: &User) -> laravel::Result<String> {
5 laravel::url::route(users::show, user.id)
6}
1use crate::http::handlers::users;
2use crate::models::User;
3 
4pub fn profile_url(user: &User) -> laravel::Result<String> {
5 laravel::url::route(users::show, user.id)
6}

Queued jobs, queued listeners, and scheduled tasks each run in a context of their own too, and so do your tests, when they take an Application argument.

Adding to the context

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

1use laravel::http::{Next, middleware};
2use laravel::prelude::*;
3 
4#[middleware]
5pub async fn identify_tenant(request: Request, next: Next) -> Response {
6 // `acme.example.com` is the `acme` tenant...
7 let tenant = request.host().split('.').next().unwrap_or_default().to_owned();
8 
9 laravel::context::add("tenant", tenant);
10 
11 next.run(request).await
12}
1use laravel::http::{Next, middleware};
2use laravel::prelude::*;
3 
4#[middleware]
5pub async fn identify_tenant(request: Request, next: Next) -> Response {
6 // `acme.example.com` is the `acme` tenant...
7 let tenant = request.host().split('.').next().unwrap_or_default().to_owned();
8 
9 laravel::context::add("tenant", tenant);
10 
11 next.run(request).await
12}

Adding a key again replaces its value. Any code that runs later in the request may read a value back with get, which returns None when the key has no value:

1use laravel::context;
2 
3let tenant: Option<String> = context::get("tenant");
1use laravel::context;
2 
3let tenant: Option<String> = context::get("tenant");

You may also check for a key with context::has("tenant"), and remove it with context::forget("tenant").

When the request ends, Laravel removes the values you added to its context. A queued job starts with the values of the code that dispatched it, so its log lines carry the same tenant as the request. When the job fails, its error is reported with those values and the ones the job added. To see how the values look in your log files, whether as plain text or JSON, check out the logging guide's section on adding context.

Hidden values

For a value that only your own code needs, use add_hidden, which keeps the value out of the logs. Read it back with get_hidden, and remove it with forget_hidden:

1use laravel::context;
2 
3context::add_hidden("plan", "pro");
4 
5let plan: Option<String> = context::get_hidden("plan");
1use laravel::context;
2 
3context::add_hidden("plan", "pro");
4 
5let plan: Option<String> = context::get_hidden("plan");

Memoizing with once

Sometimes several parts of a request need the same value, such as a count that both the handler and a shared Inertia prop show. Rather than query it twice, mark an async function with #[laravel::once]. Its body runs once per request, and later calls get a clone of the first result. You may put these functions in any module, such as src/models/mod.rs, next to your models:

1use crate::models::User;
2 
3#[laravel::once]
4pub async fn user_count() -> laravel::Result<u64> {
5 User::query().count().await
6}
1use crate::models::User;
2 
3#[laravel::once]
4pub async fn user_count() -> laravel::Result<u64> {
5 User::query().count().await
6}

The body runs once even when several callers ask at the same time. The result is only remembered for the current request, so the next request runs the body again. once remembers an error like any other result, so a failed query isn't retried until the next request.

Each caller gets a clone of the result, so the value must implement Clone. When it doesn't, or when it's large, such as a report built from thousands of rows, return it in an Arc. Every caller then shares the one value, and cloning the Arc only copies a pointer:

1use std::sync::Arc;
2 
3use crate::reports::SalesReport;
4 
5#[laravel::once]
6pub async fn sales_report() -> laravel::Result<Arc<SalesReport>> {
7 Ok(Arc::new(SalesReport::build().await?))
8}
1use std::sync::Arc;
2 
3use crate::reports::SalesReport;
4 
5#[laravel::once]
6pub async fn sales_report() -> laravel::Result<Arc<SalesReport>> {
7 Ok(Arc::new(SalesReport::build().await?))
8}

Keyed values

When the function takes arguments, once remembers a separate result for each set of arguments. Calling find_user(1) twice in a request queries the database once, while find_user(2) runs its own query and remembers its own result:

1use crate::models::User;
2 
3#[laravel::once]
4pub async fn find_user(id: i64) -> laravel::Result<Option<User>> {
5 User::find(id).await
6}
1use crate::models::User;
2 
3#[laravel::once]
4pub async fn find_user(id: i64) -> laravel::Result<Option<User>> {
5 User::find(id).await
6}

Arguments must be owned values that implement Hash, such as an i64 ID or a String. For example, pass user.id rather than a whole User, and slug.to_owned() rather than a &str.

Once closures

To memoize a value in the middle of a function, call laravel::once with a closure, or laravel::once_for with a key and a closure that receives it:

1use crate::models::User;
2 
3pub async fn find_user(id: i64) -> laravel::Result<Option<User>> {
4 laravel::once_for(id, async |id| User::find(id).await).await
5}
1use crate::models::User;
2 
3pub async fn find_user(id: i64) -> laravel::Result<Option<User>> {
4 laravel::once_for(id, async |id| User::find(id).await).await
5}

The closure can't capture variables, so pass whatever the value depends on as the key instead.

Spawned tasks

A task you spawn with tokio::spawn starts without the context, because task-local values don't carry over to a new task. A helper inside it panics with a message that names the helper:

1`laravel::url::to()` can only be used inside the application: while it handles a request or runs a command, in `Application::scope`, or in a task spawned with `laravel::task::spawn`
1`laravel::url::to()` can only be used inside the application: while it handles a request or runs a command, in `Application::scope`, or in a task spawned with `laravel::task::spawn`

Use laravel::task::spawn instead. It carries the current context and tracing span into the new task:

1use laravel::task;
2 
3let handle = task::spawn(async { laravel::url::to("/users") });
4 
5let url = handle.await?;
1use laravel::task;
2 
3let handle = task::spawn(async { laravel::url::to("/users") });
4 
5let url = handle.await?;

The task shares the context, so once still computes each value only once, and the task's log lines carry the values you've added. When you're ready to run more work at once, the concurrency and tasks guide shows how to run several operations at once, and how to run work in the background without making the user wait.