Laravel (Rust)

The PostHog Rust SDK integrates with Laravel Rust 0.1 through its optional laravel feature. The integration configures a shared client from POSTHOG_* variables, adds request context to events, captures exceptions, reads Laravel features from PostHog feature flags, and flushes queued events on shutdown.

Beta: Laravel Rust 0.1 is in beta. The laravel and laravel-opentelemetry features follow Laravel Rust's beta, so a minor release of posthog may move them to a new Laravel Rust version, or change them, without a major release.

Installation

The laravel feature needs Rust 1.99 or later, as Laravel Rust does. The rest of the SDK keeps its own minimum. Add the feature to your Cargo.toml:

Cargo.toml
[dependencies]
posthog = { version = "1", features = ["laravel"] }

Register the service provider in src/app.rs, and add IdentifyUser with your user type to the middleware groups whose routes know the logged-in user:

src/app.rs
use posthog::laravel::{IdentifyUser, PostHogServiceProvider};
Application::configure()
.with_providers(|providers| {
providers.add(PostHogServiceProvider::new());
})
.with_middleware(|middleware, _| {
middleware.web(|web| {
web.append(IdentifyUser::<User>::new());
});
})

Add your project token and host to your environment:

.env
POSTHOG_PROJECT_TOKEN=<ph_project_token>
POSTHOG_HOST=https://us.i.posthog.com

Run posthog:doctor to check the configuration without a network request, and posthog:test --send to send one test event.

Configuration

The provider reads these variables into PostHogConfig. You can change them in with_config through config.section_mut::<PostHogConfig>().

VariableDefaultEffect
POSTHOG_PROJECT_TOKENnoneThe project token. Without one, the client is disabled.
POSTHOG_HOSTUS CloudThe ingestion host.
POSTHOG_ENABLEDtruefalse disables the client.
POSTHOG_TRACING_HEADERStrueWhether to read X-PostHog-Distinct-Id and X-PostHog-Session-Id.
POSTHOG_COOKIE_FALLBACKfalseWhether to read the posthog-js cookie when a request has neither tracing header.
POSTHOG_SESSION_IDLE_TIMEOUT1800Seconds a cookie session may be idle, clamped to 60 through 36000.
POSTHOG_CAPTURE_IPtrueWhether to add the request's $ip.
POSTHOG_CAPTURE_EXCEPTIONStrueWhether to capture the failures Laravel reports.
POSTHOG_CAPTURE_REQUESTSfalseWhether to capture a laravel_request event per matched request.
POSTHOG_CAPTURE_JOBSfalseWhether to capture a laravel_job event per finished queued job.

Capturing events

The provider registers one posthog::Client, which handlers, jobs, and services take as Inject<posthog::Client>. Every request runs inside a RequestContext. Use it to create events with the request's context:

Rust
use posthog::{Client, RequestContext};
async fn checkout(posthog: Inject<Client>) -> &'static str {
let context = RequestContext::current().unwrap_or_default();
posthog.capture(context.event("checkout completed"));
"ok"
}

The request context has:

  • The identity and session of the tracing headers, which are analytics context and never proof of who the user is
  • $request_method, and $request_path set to the matched route's pattern, such as /users/{user}, for routes in the web and api groups
  • $ip, from Laravel's request.ip(), which follows the application's trusted proxies, and $user_agent and $raw_user_agent
  • The groups that PostHogServiceProvider::new().with_groups(|request| ...) returns

Identifying users

IdentifyUser makes the logged-in user's auth_id the distinct ID for the rest of the request, in place of the header. A guest keeps the header identity, or the personless default without one.

IP addresses

POSTHOG_CAPTURE_IP=false only stops the SDK from sending the visitor's address. PostHog still records the address its ingestion request came from, which is your server's. To keep no IP addresses, turn on Discard client IP data in the project's IP data capture settings.

With POSTHOG_COOKIE_FALLBACK=true, a request with neither tracing header takes its identity and live session from the project's posthog-js cookie, ph_<token>_posthog. The fallback skips a visitor whose __ph_opt_in_out_<token> consent cookie is no-like, and sends an anonymous visitor's events with process_person_profile: false. It's off by default because the server can't see an opt-out that posthog-js keeps in local storage.

Queued jobs and spawned tasks

Laravel copies the request context into queued jobs, laravel::task::spawn, laravel::task::background, and the producers of Streamed::channel bodies. Start their work with posthog::laravel::with_context to use the context of the request that dispatched them. Queued jobs leave out the visitor's $ip, $user_agent, and $raw_user_agent.

Rust
#[job]
impl ShipOrder {
async fn handle(self, posthog: Inject<posthog::Client>) -> laravel::Result<()> {
posthog::laravel::with_context(async {
let context = posthog::RequestContext::current().unwrap_or_default();
posthog.capture(context.event("order shipped"));
})
.await;
Ok(())
}
}

Capturing exceptions

The provider captures each failure that Laravel reports, the errors and panics with a 5xx status, as an $exception event with the request context and $exception_source set to laravel.reportable. Errors with a client status, such as a 404, aren't captured. Errors that with_errors ignores with dont_report aren't captured either.

A panic keeps its full stack, and the event's mechanism is panic. With the SDK's own capture_panics, a panic is captured once.

A queued job that fails for good on a worker is captured once, with the context of the request that dispatched it and $exception_source set to laravel.queue_job.

With the laravel-opentelemetry feature and Laravel's opentelemetry feature exporting traces, exceptions carry the $trace_id and $span_id of the span active when the failure was reported.

Feature flags

With FEATURE_STORE=posthog, Laravel's #[flag] features read PostHog's feature flags for each scope, with the ID in the scope's key as the distinct ID. A boolean flag is the feature's bool, and a multivariate flag's variant is a JSON string.

A flag that PostHog doesn't return, and every guest or application-wide feature, falls back to its #[flag] function. When PostHog can't evaluate a scope's flags, the store logs a warning and the #[flag] functions decide, so the request doesn't fail.

A team and a user with the same ID are the same PostHog person, so give non-user scopes IDs no user has, such as team-42. PostHog's flags are read-only here: activating, forgetting, or purging a feature logs a warning and changes nothing.

Server events

POSTHOG_CAPTURE_REQUESTS and POSTHOG_CAPTURE_JOBS turn on these server events:

EventProperties
laravel_requestroute (the matched pattern), method, status_code, duration_ms
laravel_jobname, outcome (success or failed), attempts, duration_ms

Only routes matched in the web and api groups are captured. Laravel Rust 0.1 dispatches no login or logout events, so there are no auth events.

Delivery

The client sends queued events every 5 seconds or once 100 are queued. The provider flushes them when the server or a queue worker stops, after the requests or jobs in progress finish.

Console commands don't run ticks or carry a request's context, so a command that captures events should scope a RequestContext itself and call posthog.flush().await before it returns.

Testing

PostHogFake records the events an application captures instead of sending them. It's behind the laravel-testing feature, so enable it for tests only:

Cargo.toml
[dependencies]
posthog = { version = "1", features = ["laravel"] }
[dev-dependencies]
posthog = { version = "1", features = ["laravel", "laravel-testing"] }
Rust
use posthog::laravel::{PostHogFake, PostHogServiceProvider};
let posthog = PostHogFake::new();
let app = Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_providers(|providers| {
providers.add(PostHogServiceProvider::new());
})
.with_services({
let posthog = posthog.clone();
move |app| posthog.install(app)
})
.create();
app.get("/checkout").await.assert_ok();
posthog.assert_captured("checkout completed");

The fake records every capture, including AI and immediate captures, with the request context applied and groups in $groups, as it would be sent.

Still have questions?

Was this page useful?