> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Laravel (Rust) Canonical URL: https://posthog.com/docs/libraries/laravel-rs > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). ## On this page - [Installation](#installation) - [Configuration](#configuration) - [Capturing events](#capturing-events) - [Capturing exceptions](#capturing-exceptions) - [Feature flags](#feature-flags) - [Server events](#server-events) - [Delivery](#delivery) - [Testing](#testing) The PostHog [Rust SDK](https://posthog.com/docs/libraries/rust.md) integrates with [Laravel Rust](https://laravel.com/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 ```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 ```rust use posthog::laravel::{IdentifyUser, PostHogServiceProvider}; Application::configure() .with_providers(|providers| { providers.add(PostHogServiceProvider::new()); }) .with_middleware(|middleware, _| { middleware.web(|web| { web.append(IdentifyUser::::new()); }); }) ``` Add your project token and host to your environment: .env ```bash POSTHOG_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::()`. | Variable | Default | Effect | | --- | --- | --- | | `POSTHOG_PROJECT_TOKEN` | none | The project token. Without one, the client is disabled. | | `POSTHOG_HOST` | US Cloud | The ingestion host. | | `POSTHOG_ENABLED` | `true` | `false` disables the client. | | `POSTHOG_TRACING_HEADERS` | `true` | Whether to read `X-PostHog-Distinct-Id` and `X-PostHog-Session-Id`. | | `POSTHOG_COOKIE_FALLBACK` | `false` | Whether to read the posthog-js cookie when a request has neither tracing header. | | `POSTHOG_SESSION_IDLE_TIMEOUT` | `1800` | Seconds a cookie session may be idle, clamped to 60 through 36000. | | `POSTHOG_CAPTURE_IP` | `true` | Whether to add the request's `$ip`. | | `POSTHOG_CAPTURE_EXCEPTIONS` | `true` | Whether to capture the failures Laravel reports. | | `POSTHOG_CAPTURE_REQUESTS` | `false` | Whether to capture a `laravel_request` event per matched request. | | `POSTHOG_CAPTURE_JOBS` | `false` | Whether 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`. 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) -> &'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](https://posthog.com/docs/libraries/js/config.md#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. ### Cookie fallback 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__posthog`. The fallback skips a visitor whose `__ph_opt_in_out_` 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) -> 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](https://posthog.com/docs/feature-flags.md) 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: | Event | Properties | | --- | --- | | `laravel_request` | `route` (the matched pattern), `method`, `status_code`, `duration_ms` | | `laravel_job` | `name`, `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 ```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.