PHPackages                             philiprehberger/laravel-correlation-id - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. philiprehberger/laravel-correlation-id

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

philiprehberger/laravel-correlation-id
======================================

Laravel middleware that generates or propagates correlation IDs for request tracing with automatic log context injection

v1.2.0(2mo ago)260MITPHPPHP ^8.2CI passing

Since Mar 6Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/laravel-correlation-id)[ Packagist](https://packagist.org/packages/philiprehberger/laravel-correlation-id)[ Docs](https://github.com/philiprehberger/laravel-correlation-id)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-laravel-correlation-id/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (16)Versions (9)Used By (0)

Laravel Correlation ID
======================

[](#laravel-correlation-id)

[![Tests](https://github.com/philiprehberger/laravel-correlation-id/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/laravel-correlation-id/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/ad785233989807580b4f48b791caac0e830c8c76c44e41a37cf2a8091529e60e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f6c61726176656c2d636f7272656c6174696f6e2d69642e737667)](https://packagist.org/packages/philiprehberger/laravel-correlation-id)[![Last updated](https://camo.githubusercontent.com/dcbb5ad99a3a133efbf0e3cdb0ff89d36caa0e531c53c3ef651bb58acc6543cc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f6c61726176656c2d636f7272656c6174696f6e2d6964)](https://github.com/philiprehberger/laravel-correlation-id/commits/main)

Laravel middleware that generates or propagates correlation IDs for request tracing with automatic log context injection.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12

Installation
------------

[](#installation)

```
composer require philiprehberger/laravel-correlation-id
```

The service provider is registered automatically via Laravel package auto-discovery.

Optionally publish the config:

```
php artisan vendor:publish --tag=correlation-id-config
```

Usage
-----

[](#usage)

```
use PhilipRehberger\CorrelationId\AddCorrelationId;

// Register the middleware in bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->prepend(AddCorrelationId::class);
})
```

### Accessing the Correlation ID

[](#accessing-the-correlation-id)

```
use PhilipRehberger\CorrelationId\CorrelationId;

// Via the helper class
$id = CorrelationId::get();
CorrelationId::set('my-custom-id');

// Via the request macro
$id = $request->correlationId();
```

### Configuration

[](#configuration)

```
// config/correlation-id.php
return [
    'request_headers' => ['X-Request-Id', 'X-Correlation-ID'],
    'response_header' => 'X-Request-Id',
    'log_context_key' => 'correlation_id',
    'sentry'          => true,
    'generator'       => 'uuid',
];
```

### How It Works

[](#how-it-works)

1. The middleware inspects incoming request headers in the order defined by `request_headers`.
2. The first non-empty value found is used as-is (propagation path).
3. When no matching header is present, a new ID is generated using the configured generator.
4. The ID is stored as a request attribute and shared with the log context.
5. After the handler returns, the ID is written to the response header defined by `response_header`.

### Custom ID Generator

[](#custom-id-generator)

Control how new correlation IDs are generated when no upstream header is present:

```
// config/correlation-id.php

// UUID v4 (default)
'generator' => 'uuid',

// UUID v7 (time-ordered, sortable)
'generator' => 'uuid7',

// ULID (compact, sortable)
'generator' => 'ulid',

// Custom callable
'generator' => fn () => 'prefix-' . bin2hex(random_bytes(16)),
```

### Queue Job Propagation

[](#queue-job-propagation)

Propagate the correlation ID from the dispatching context into queued jobs:

```
use PhilipRehberger\CorrelationId\Concerns\TracksCorrelationId;
use PhilipRehberger\CorrelationId\Middleware\CorrelationIdJobMiddleware;

class ProcessOrder implements ShouldQueue
{
    use TracksCorrelationId;

    public function middleware(): array
    {
        return [new CorrelationIdJobMiddleware];
    }

    public function handle(): void
    {
        // CorrelationId::get() returns the same ID from dispatch time
    }
}
```

The `TracksCorrelationId` trait captures the current correlation ID when the job is created. The `CorrelationIdJobMiddleware` restores it when the job runs on a worker.

### HTTP Client Propagation

[](#http-client-propagation)

Automatically forward the correlation ID to outgoing HTTP requests made with Laravel's HTTP client:

```
use Illuminate\Support\Facades\Http;
use PhilipRehberger\CorrelationId\CorrelationId;

$response = Http::withMiddleware(CorrelationId::httpMiddleware())
    ->get('https://api.example.com/orders');

// Uses a custom header name
$response = Http::withMiddleware(CorrelationId::httpMiddleware('X-Request-Id'))
    ->get('https://api.example.com/orders');
```

The middleware adds the `X-Correlation-ID` header (or your custom header) to every outgoing request.

### Trace Spans

[](#trace-spans)

Track the timing of operations within a request using lightweight trace spans:

```
use PhilipRehberger\CorrelationId\CorrelationId;

$span = CorrelationId::startSpan('external-api-call', ['url' => $url]);

$response = Http::get($url);

$ended = CorrelationId::endSpan($span);

// Access span data
$ended->durationMs();  // Duration in milliseconds
$ended->toArray();     // Full array representation

// Retrieve all completed spans
$spans = CorrelationId::spans();

// Clear spans (e.g., between tests)
CorrelationId::clearSpans();
```

Spans are immutable value objects. Calling `endSpan()` returns a new instance with the end time set and stores it for later retrieval.

### Sentry Integration

[](#sentry-integration)

When `sentry/sentry-laravel` is installed and `'sentry' => true`, the middleware sets `correlation_id` as a tag on every Sentry event captured during the request.

API
---

[](#api)

Class / MethodDescription`AddCorrelationId` middlewareGenerates or propagates the correlation ID and injects it into logs and responses`CorrelationId::get()`Read the current correlation ID (`null` if not yet set)`CorrelationId::set(string $id)`Override the correlation ID (useful in tests or CLI commands)`CorrelationId::generate()`Generate a new correlation ID using the configured generator`CorrelationId::reset()`Clear the correlation ID and all trace spans for the current request`CorrelationId::httpMiddleware(?string $headerName)`Returns a Guzzle middleware closure for HTTP client propagation`CorrelationId::startSpan(string $name, array $metadata)`Start a new trace span linked to the current correlation ID`CorrelationId::endSpan(Span $span)`End a span and store it for retrieval`CorrelationId::spans()`Get all completed trace spans`CorrelationId::clearSpans()`Clear all stored trace spans`$request->correlationId()`Request macro that returns the current correlation ID`TracksCorrelationId` traitCaptures the correlation ID at dispatch time for queue jobs`CorrelationIdJobMiddleware`Queue job middleware that restores the correlation ID`PropagateCorrelationId::handler()`Static factory for the HTTP client propagation middleware`Span` value objectImmutable span with `name`, `durationMs()`, `toArray()`Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/laravel-correlation-id)

🐛 [Report issues](https://github.com/philiprehberger/laravel-correlation-id/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/laravel-correlation-id/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

43

—

FairBetter than 90% of packages

Maintenance88

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

8

Last Release

76d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (19 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

middlewarelaravelloggingtracingcorrelation-idrequest id

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-laravel-correlation-id/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-laravel-correlation-id/health.svg)](https://phpackages.com/packages/philiprehberger-laravel-correlation-id)
```

###  Alternatives

[sentry/sentry-laravel

Laravel SDK for Sentry (https://sentry.io)

1.3k122.6M185](/packages/sentry-sentry-laravel)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
