Skip to main content
ImmutableLog logo
← Back
LaravelPHP

Laravel Integration

Integrate ImmutableLog into any Laravel application with a global terminable middleware. `handle()` only marks the start; the event is built and sent in `terminate()`, which Laravel calls after delivering the response to the client. A send failure only produces a `Log::warning`. Read the PHP-FPM section before using it in production.

Installation

There is no Composer package: you copy the `ImmutableLogMiddleware.php` file from GitHub to `app/Http/Middleware/ImmutableLogMiddleware.php`. It only uses `ext-curl` and `ext-json` (present in the official PHP images) and Laravel itself (10 or newer; tested on 13). PHP 8.1+. The file declares `namespace App\Http\Middleware;`.

bash
app/Http/Middleware/ImmutableLogMiddleware.php   # conteúdo do ImmutableLogMiddleware.php

Middleware code

This is the whole file. `handle()` only marks the request start (except `OPTIONS` and the `skip_paths`); `terminate()` builds the event and sends it after the response. An unhandled exception also produces an event, with status 500 and `error_*`.

php
<?php

// ImmutableLog middleware for Laravel (10, 11, 12).
//
// Copy this file to app/Http/Middleware/ImmutableLogMiddleware.php and register it as a
// global middleware (see the README). Uses only ext-curl and ext-json; no Composer package.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class ImmutableLogMiddleware
{
    private const DEFAULT_API_URL = 'https://api.immutablelog.com';
    private const DEFAULT_SKIP_PATHS = ['/health', '/healthz', '/up'];
    private const TIMEOUT_SECONDS = 5;
    private const MAX_ERROR_MESSAGE = 500;
    private const MAX_PATH = 2048;
    private const MAX_USER_AGENT = 512;
    private const MAX_TRAIL = 256;

    public function handle(Request $request, Closure $next): Response
    {
        if (! $this->skip($request)) {
            $request->attributes->set('imtbl.started_at', microtime(true));
        }

        return $next($request);
    }

    /**
     * Runs after the response was sent to the client (under PHP-FPM, after
     * fastcgi_finish_request()), so the POST to ImmutableLog never delays it.
     */
    public function terminate(Request $request, Response $response): void
    {
        if (! $request->attributes->has('imtbl.started_at')) {
            return; // skipped (OPTIONS, health) or the request never reached handle()
        }

        try {
            $apiKey = (string) $this->setting('key', 'IMTBL_API_KEY', '');
            if ($apiKey === '') {
                return;
            }
            $event = $this->buildEvent($request, $response);
            $this->send(
                rtrim((string) $this->setting('url', 'IMTBL_URL', self::DEFAULT_API_URL), '/').'/v1/events',
                $apiKey,
                $event['request_id'],
                $event['body']
            );
        } catch (\Throwable $e) {
            Log::warning('[ImmutableLog] failed to send event: '.$e->getMessage());
        }
    }

    private function skip(Request $request): bool
    {
        if ($request->isMethod('OPTIONS')) {
            return true;
        }
        $skip = config('services.immutablelog.skip_paths', self::DEFAULT_SKIP_PATHS);

        return in_array('/'.ltrim($request->path(), '/'), (array) $skip, true);
    }

    /** config('services.immutablelog.<key>') first (works with config:cache), then the env var. */
    private function setting(string $key, string $envName, string $default): string
    {
        $value = config("services.immutablelog.$key");
        if ($value === null || $value === '') {
            $value = env($envName);
        }

        return ($value === null || $value === '') ? $default : (string) $value;
    }

    /** @return array{request_id: string, body: string} */
    private function buildEvent(Request $request, Response $response): array
    {
        $status = $response->getStatusCode();
        $kind = $status >= 400 ? 'error' : ($status >= 300 ? 'info' : ($status >= 200 ? 'success' : 'info'));
        $method = $request->getMethod();
        $path = mb_substr('/'.ltrim($request->path(), '/'), 0, self::MAX_PATH);
        $requestId = (string) Str::uuid();
        $latencyMs = (int) round((microtime(true) - (float) $request->attributes->get('imtbl.started_at')) * 1000);
        $clientIp = self::clientIp(
            $request->headers->get('X-Forwarded-For'),
            $request->headers->get('X-Real-IP'),
            $request->server('REMOTE_ADDR')
        );
        $service = $this->setting('service', 'IMTBL_SERVICE_NAME', 'laravel-service');
        $env = $this->setting('env', 'IMTBL_ENV', 'production');

        // Route template: "users/{id}" from the matched route; null on a 404.
        $route = $request->route();
        $httpRoute = ($route !== null && method_exists($route, 'uri')) ? '/'.ltrim($route->uri(), '/') : $path;

        $eventName = $request->attributes->get('imtbl.event_name') ?: "http.$method.$path";
        $trailSource = $request->attributes->get('imtbl.trail');
        if ($trailSource === null && config('services.immutablelog.trust_trail_header', false)) {
            $trailSource = $request->headers->get('X-Imtbl-Trail');
        }
        $trail = self::sanitizeTrail($trailSource);

        // Laravel attaches the exception to the response it renders for it.
        $exception = property_exists($response, 'exception') ? $response->exception : null;
        $errorType = $exception instanceof \Throwable ? get_class($exception) : null;
        $errorMessage = $exception instanceof \Throwable ? $exception->getMessage() : null;

        $payload = [
            'id' => (string) Str::uuid(),
            'kind' => $kind,
            'message' => "$method $path -> $status",
            'timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'context' => [
                'ip' => $clientIp ?? 'unknown',
                'user_agent' => mb_substr((string) $request->userAgent(), 0, self::MAX_USER_AGENT),
            ],
            'request' => ['request_id' => $requestId, 'method' => $method, 'path' => $path],
            'metrics' => ['latency_ms' => $latencyMs, 'status_code' => $status],
            'severity' => $kind === 'error' ? 'high' : 'low',
        ];
        if ($kind === 'error') {
            $payload['error'] = [
                'status_code' => $status,
                'retryable' => in_array($status, [408, 429, 500, 502, 503, 504], true),
            ];
            if ($errorType !== null) {
                $payload['error']['exception'] = $errorType;
                $payload['error']['exception_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }

        // meta is a string -> string map in the core: every value is cast with (string).
        // http_status goes as "200", never as the integer 200.
        $meta = [
            'type' => $kind,
            'event_type' => $kind,
            'event_name' => (string) $eventName,
            'service' => (string) $service,
            'request_id' => $requestId,
            // "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
            'env' => (string) $env,
            'environment' => (string) $env,
            'http_method' => $method,
            'http_status' => (string) $status,
            'http_route' => (string) $httpRoute,
            'log_level' => self::logLevel($kind),
        ];
        if ($clientIp !== null) {
            $meta['client_ip'] = $clientIp;
        }
        if ($errorType !== null) {
            $meta['error_type'] = $errorType;
            if ((string) $errorMessage !== '') {
                $meta['error_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }
        if ($trail !== null) {
            $meta['immutable_trail'] = $trail;
        }

        $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR;
        $body = json_encode(['payload' => json_encode($payload, $flags), 'meta' => $meta], $flags);

        return ['request_id' => $requestId, 'body' => $body];
    }

    private function send(string $url, string $apiKey, string $idempotencyKey, string $body): void
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer '.$apiKey,
                'Idempotency-Key: '.$idempotencyKey,
            ],
            CURLOPT_RETURNTRANSFER => true,
            // The send runs in terminate(), after the client got the response, but it still holds
            // the PHP-FPM worker until it finishes: keep the timeout short.
            CURLOPT_CONNECTTIMEOUT_MS => 1000,
            CURLOPT_TIMEOUT_MS => (int) ((float) config('services.immutablelog.timeout', self::TIMEOUT_SECONDS) * 1000),
        ]);
        $result = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($result === false) {
            Log::warning('[ImmutableLog] failed to send event: '.curl_error($ch));
        } elseif ($status >= 400) {
            Log::warning("[ImmutableLog] event rejected: HTTP $status");
        }
        curl_close($ch);
    }

    /**
     * client_ip for the SIEM: first entry of X-Forwarded-For, then X-Real-IP, then REMOTE_ADDR.
     * Only a bare IP is returned (no port): the SIEM drops "ip:port" silently. The headers are
     * read directly, without TrustProxies; see "Proxy e X-Forwarded-For" in the README.
     */
    public static function clientIp(?string $xff, ?string $realIp, ?string $remoteAddr): ?string
    {
        $first = $xff !== null ? explode(',', $xff)[0] : null;

        return self::bareIp($first) ?? self::bareIp($realIp) ?? self::bareIp($remoteAddr);
    }

    /** "203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP. */
    private static function bareIp(?string $raw): ?string
    {
        $s = trim((string) $raw);
        if ($s === '') {
            return null;
        }
        if ($s[0] === '[') {
            $end = strpos($s, ']');
            $s = $end === false ? '' : substr($s, 1, $end - 1);
        } elseif (substr_count($s, ':') === 1) {
            $s = explode(':', $s)[0];
        }
        if (filter_var($s, FILTER_VALIDATE_IP) === false) {
            return null;
        }
        // "::ffff:10.0.0.1" -> "10.0.0.1"
        if (stripos($s, '::ffff:') === 0 && filter_var(substr($s, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
            return substr($s, 7);
        }

        return $s;
    }

    /** The core rejects a trail that is empty, longer than 256 chars or contains ':'. */
    private static function sanitizeTrail(mixed $value): ?string
    {
        if (! is_scalar($value)) {
            return null;
        }
        $s = mb_substr(str_replace(':', '-', trim((string) $value)), 0, self::MAX_TRAIL);

        return $s === '' ? null : $s;
    }

    private static function logLevel(string $kind): string
    {
        return match ($kind) {
            'error' => 'error',
            'warning' => 'warn',
            'debug' => 'debug',
            default => 'info',
        };
    }
}

Middleware registration

On Laravel 11 or newer, register it in `bootstrap/app.php`. On Laravel 10, add it to the `$middleware` property of `app/Http/Kernel.php`. It must be global: `terminate()` only runs for middleware registered on the kernel.

php
<?php
// Laravel 11 ou mais novo: bootstrap/app.php
use App\Http\Middleware\ImmutableLogMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    // ...
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->append(ImmutableLogMiddleware::class);   // global
    })
    ->create();

// Laravel 10: app/Http/Kernel.php
// protected $middleware = [
//     // ...
//     \App\Http\Middleware\ImmutableLogMiddleware::class,
// ];

The middleware reads `config('services.immutablelog.*')` first and only then `env()`. Use `config/services.php`: with `php artisan config:cache` the `.env` is no longer loaded at runtime, and only the config survives.

php
// config/services.php
'immutablelog' => [
    'key'     => env('IMTBL_API_KEY'),
    'url'     => env('IMTBL_URL', 'https://api.immutablelog.com'),
    'service' => env('IMTBL_SERVICE_NAME', 'laravel-service'),
    'env'     => env('IMTBL_ENV', 'production'),
    'timeout' => 2,                       // segundos; ver a seção sobre PHP-FPM
    // 'skip_paths' => ['/health', '/up'],
    // 'trust_trail_header' => false,
],

# .env
IMTBL_API_KEY=iml_live_xxxxxxxxxxxxxxxx
IMTBL_SERVICE_NAME=meu-servico-laravel
IMTBL_ENV=production
VariableRequiredDescription
IMTBL_API_KEYYesImmutableLog API key, with the `events:write` scope
IMTBL_URLNoAPI base URL (default `https://api.immutablelog.com`)
IMTBL_SERVICE_NAMENoService name (`meta.service`); default `laravel-service`
IMTBL_ENVNoEnvironment (`meta.environment` and `meta.env`); default `production`

Without a key, the middleware sends nothing. The optional `services.immutablelog` keys are `skip_paths` (exact match; default `/health`, `/healthz` and `/up`), `trust_trail_header` and `timeout` (seconds; default 5).

Never put the key in code or in the repository: keep .env out of git, or use a secrets manager. `php artisan serve` only forwards the .env variables and a fixed list to the built-in server; an IMTBL_API_KEY exported only in the shell does not reach PHP. PHP-FPM, by default (`clear_env = yes`), also drops the process environment. In both cases, use .env or config/services.php.

How it works

handle()

Marks imtbl.started_at in the request attributes (except OPTIONS and skip_paths)

next($request)

The app processes and the response is sent to the client

terminate()

Reads status, route, exception and markers; builds the event; POST via cURL

Idempotency-Key

A new UUID per event (Str::uuid()), equal to meta.request_id. The incoming X-Request-Id is not used, because it comes from the caller and two different events with the same value would be discarded as a duplicate

body

The middleware never reads the request body: no content, no hash

Sending, PHP-FPM and response time

PHP has no background thread: the POST runs in the same process, in `terminate()`. How you serve the application changes the effect.

How it is servedEffect of sending
PHP-FPMThe client gets the response without waiting for the send (`fastcgi_finish_request()` runs first). But the FPM worker stays busy until the send finishes, at most the timeout. With a slow ImmutableLog, workers get stuck and the following requests wait in the pool queue (the default is 5 workers).
php artisan serve / php -SThere is no `fastcgi_finish_request()`: the connection only closes after the send. With a slow ImmutableLog, every response is delayed up to the timeout (measured: 5 s with the core stalled). Use it in development only.

Keep the timeout low (`services.immutablelog.timeout`, in seconds; the file default is 5) and size the FPM pool. To isolate it for good, move the send to a queue (a job via `dispatch()`), which is not in this file. With ImmutableLog simply down (connection refused), there is no visible effect.

Custom event and trail

Set the `imtbl.event_name` and `imtbl.trail` request attributes in any controller or route closure. `terminate()` reads these values when building the event.

php
public function store(Request $request)
{
    $request->attributes->set('imtbl.event_name', 'payment.created');
    $request->attributes->set('imtbl.trail', 'order-7782');

    return response()->json(['ok' => true], 201);
}

Auto default: http.METHOD.path.

Immutable trail (immutable_trail)

A trail groups related events into a single auditable timeline and goes in `meta.immutable_trail`. Set the `imtbl.trail` request attribute. The value goes through `sanitizeTrail` before sending.

php
Route::post('/flows/{id}/run', function (Request $request, string $id) {
    $request->attributes->set('imtbl.trail', "flow-{$id}");
    // ... business logic ...
    return response()->json(['status' => 'ok']);
});

The trail cannot be empty, exceed 256 characters, or contain `:`, and violations return `400 invalid_immutable_trail`. That is why `sanitizeTrail` replaces `:` with `-`, truncates at 256 and omits the key if it ends up empty.

The `X-Imtbl-Trail` header is optional and off by default. It is only read with `'trust_trail_header' => true` em `config/services.php`, and only when the controller did not set the trail. The header comes from whoever calls the service, so any caller could hang events on another caller's trail within the same tenant. Turn it on only when the service receives calls exclusively from your own internal services.

Response and status codes

The ingestion API is asynchronous. Success returns 202 (new) or 200 (idempotent duplicate). Sending happens in `terminate()` and a rejection only produces a `Log::warning`, so these codes matter mostly if you send events manually.

StatusMeaning
202Event accepted and queued (new)
200Idempotency-Key already exists (duplicate: true)
400Missing/empty Idempotency-Key or invalid_immutable_trail
403Inactive/expired subscription, scope or retention
413payload_too_large (server limit: 16KB)
429monthly_limit_exceeded, do not retry
503mempool_full, transient, retryable

meta fields

Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.

Field in metaWhat it does in the SIEM
event_nameThe event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below.
immutable_trailBecomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user).
typeEvent severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.)
http_method, http_status, http_route, log_level, environment, error_type, error_messageSent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error.
service, env, request_idMetadata: indexed and queryable in the dashboard (search/filters).

client_ip: end-user IP

The problem it solves

Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)

The solution

The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.

How the SIEM handles it

  • Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g. 1.2.3.4:5678) is also silently discarded.
  • Writes to source.ip with maximum precedence (see order below).
  • Stamps imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge.
  • Feeds GeoIP, threat intel and IP-based detection rules.
source.ip precedence:client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IP

Provenance and trust

client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.

How to obtain the IP in your backend

Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).

Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to source.ip.

php
function bare_ip(?string $value): ?string {
    $v = trim((string) $value);
    if ($v === '') return null;
    if ($v[0] === '[') {
        $end = strpos($v, ']');
        if ($end === false) return null;
        $rest = substr($v, $end + 1);
        if ($rest !== '' && !preg_match('/^:\d+$/', $rest)) return null;
        $v = substr($v, 1, $end - 1);
    } elseif (substr_count($v, ':') === 1) {
        $v = explode(':', $v, 2)[0]; // 1.2.3.4:5678 -> 1.2.3.4
    }
    if (strpos($v, '%') !== false) return null; // zona IPv6 (fe80::1%eth0) nao e IP puro
    return filter_var($v, FILTER_VALIDATE_IP) !== false ? $v : null;
}

// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
function client_ip(): ?string {
    $xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
    if ($xff !== '' && ($ip = bare_ip(explode(',', $xff)[0])) !== null) return $ip;
    if (($ip = bare_ip($_SERVER['HTTP_X_REAL_IP'] ?? null)) !== null) return $ip;
    return bare_ip($_SERVER['REMOTE_ADDR'] ?? null);
}

$meta = ['event_name' => 'user.login'];
$ip = client_ip();
if ($ip !== null) {
    $meta['client_ip'] = $ip; // sem IP valido, omita a chave (nunca "unknown")
}

Payload example

json
{
  "payload": "{\"user\":\"bob\",\"action\":\"login\"}",
  "meta": {
    "event_name": "user.login",
    "client_ip": "179.110.4.205",
    "immutable_trail": "user-bob"
  }
}

PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.

This documentation reflects the current integration behavior. For questions or advanced integrations, contact the support team.

Back to PHP