PHPackages                             perfbase/laravel - 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. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. perfbase/laravel

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

perfbase/laravel
================

A Laravel extension for the Perfbase profiling tool.

v1.5.0(2mo ago)11.1kApache-2.0PHPPHP &gt;=7.4 &lt;8.6CI passing

Since Nov 7Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/perfbaseorg/laravel)[ Packagist](https://packagist.org/packages/perfbase/laravel)[ Docs](https://github.com/perfbaseorg/laravel)[ RSS](/packages/perfbase-laravel/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (10)Dependencies (14)Versions (28)Used By (0)

 [ ![Perfbase](https://camo.githubusercontent.com/a4e071fd1246cf5c68819015801139400d74b208b76a07ba8c5945d6e4ffd3ba/68747470733a2f2f63646e2e70657266626173652e636f6d2f696d672f6c6f676f2d66756c6c2e737667) ](https://perfbase.com)

### Perfbase for Laravel

[](#perfbase-for-laravel)

 Laravel integration for [Perfbase](https://perfbase.com).

 [![Packagist Version](https://camo.githubusercontent.com/dd414beeacf08d31e374eb36db47990401ce9b1fd24610afaa4e2b529b7afcc9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70657266626173652f6c61726176656c)](https://packagist.org/packages/perfbase/laravel) [![License](https://camo.githubusercontent.com/4ae0be02d71c1ae0a1134e7463bbc6d076c872cece6c4c32458af10518fad835/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f70657266626173652f6c61726176656c)](https://github.com/perfbaseorg/laravel/blob/main/LICENSE.txt) [![CI](https://camo.githubusercontent.com/bd58728f8d7ae43b103937b72b952d0b5a36a793e3bb563a5cba8db50fccbe2f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70657266626173656f72672f6c61726176656c2f63692e796d6c3f6272616e63683d6d61696e)](https://github.com/perfbaseorg/laravel/actions/workflows/ci.yml) [![PHP Version](https://camo.githubusercontent.com/1150142271e92a6b30ce3ef37f5548f25d15d1e9cd200eea972f746cc7a2c40a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d372e342532422d626c7565)](https://camo.githubusercontent.com/1150142271e92a6b30ce3ef37f5548f25d15d1e9cd200eea972f746cc7a2c40a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d372e342532422d626c7565) [![Laravel Version](https://camo.githubusercontent.com/77ab3874e58ddc0e5998a4aef819b2b54e70ee84954a47a684fbf25db878e56c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d382e782d2d31332e782d626c7565)](https://camo.githubusercontent.com/77ab3874e58ddc0e5998a4aef819b2b54e70ee84954a47a684fbf25db878e56c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d382e782d2d31332e782d626c7565)

This package is a thin adapter over [`perfbase/php-sdk`](https://packagist.org/packages/perfbase/php-sdk). It wires Laravel request, Artisan command, and queue job lifecycles into the SDK and leaves trace transport, submission, and extension handling to the shared SDK.

What it profiles
----------------

[](#what-it-profiles)

- HTTP requests when the Perfbase middleware is installed
- Artisan commands through Laravel console events
- Queue jobs through Laravel queue events
- Manual custom spans through the `Perfbase` facade or injected SDK client

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

[](#requirements)

- PHP `7.4` to `8.5`
- Laravel `8.x`, `9.x`, `10.x`, `11.x`, `12.x`, or `13.x`
- `ext-json`
- `ext-zlib`
- `ext-perfbase`

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

[](#installation)

Install the package from Packagist:

```
composer require perfbase/laravel:^1.0
```

Install the native Perfbase extension if it is not already available:

```
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"
```

Restart PHP-FPM, Octane workers, Horizon workers, or your web server after installing the extension.

Publish the config file:

```
php artisan vendor:publish --tag="perfbase-config"
```

Add the minimum environment variables:

```
PERFBASE_ENABLED=true
PERFBASE_API_KEY=your_api_key_here
PERFBASE_SAMPLE_RATE=0.1
```

### HTTP middleware

[](#http-middleware)

HTTP profiling is enabled only when the middleware is present.

For Laravel 8 to 10, add it to `app/Http/Kernel.php`:

```
protected $middleware = [
    // ...
    \Perfbase\Laravel\Middleware\PerfbaseMiddleware::class,
];
```

Or attach it to a middleware group:

```
protected $middlewareGroups = [
    'web' => [
        // ...
        \Perfbase\Laravel\Middleware\PerfbaseMiddleware::class,
    ],
];
```

For Laravel 11+, register it in `bootstrap/app.php`:

```
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Perfbase\Laravel\Middleware\PerfbaseMiddleware;

return Application::configure(dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(PerfbaseMiddleware::class);
    })
    ->create();
```

Artisan command and job profiling do not need middleware. They are wired through the package service provider.

Configuration
-------------

[](#configuration)

Published config lives at `config/perfbase.php`.

```
return [
    'enabled' => env('PERFBASE_ENABLED', false),
    'debug' => env('PERFBASE_DEBUG', false),
    'log_errors' => env('PERFBASE_LOG_ERRORS', true),
    'api_key' => env('PERFBASE_API_KEY'),
    'sample_rate' => env('PERFBASE_SAMPLE_RATE', 0.1),
    'profile_http_status_codes' => [...range(200, 299), ...range(500, 599)],
    'timeout' => env('PERFBASE_TIMEOUT', 5),
    'proxy' => env('PERFBASE_PROXY'),
    'flags' => env('PERFBASE_FLAGS', \Perfbase\SDK\FeatureFlags::DefaultFlags),
    'include' => [
        'http' => ['.*'],
        'artisan' => ['.*'],
        'jobs' => ['.*'],
    ],
    'exclude' => [
        'http' => [],
        'artisan' => ['queue:work'],
        'jobs' => [],
    ],
];
```

### Environment variables

[](#environment-variables)

VariableDefaultPurpose`PERFBASE_ENABLED``false`Global on/off switch`PERFBASE_API_KEY``null`Perfbase API key`PERFBASE_SAMPLE_RATE``0.1`Sampling rate from `0.0` to `1.0``PERFBASE_DEBUG``false`Re-throw profiling exceptions`PERFBASE_LOG_ERRORS``true`Log profiling failures when debug is off`PERFBASE_TIMEOUT``5`Trace submission timeout in seconds`PERFBASE_PROXY``null`Optional outbound proxy`PERFBASE_FLAGS``FeatureFlags::DefaultFlags`Perfbase extension feature flags`profile_http_status_codes` is configured in `config/perfbase.php`. The default `[...range(200, 299), ...range(500, 599)]` submits successful responses and server errors, while dropping common noisy client responses such as `404`. Add codes such as `404` if you want to keep them.

### Feature flags

[](#feature-flags)

```
use Perfbase\SDK\FeatureFlags;

'flags' => FeatureFlags::DefaultFlags;
'flags' => FeatureFlags::AllFlags;
'flags' => FeatureFlags::TrackCpuTime | FeatureFlags::TrackPdo;
```

Common flags:

- `UseCoarseClock`
- `TrackCpuTime`
- `TrackMemoryAllocation`
- `TrackPdo`
- `TrackHttp`
- `TrackCaches`
- `TrackMongodb`
- `TrackElasticsearch`
- `TrackQueues`
- `TrackAwsSdk`
- `TrackFileOperations`
- `TrackFileCompilation`
- `TrackFileDefinitions`
- `TrackExceptions`

### Include and exclude filters

[](#include-and-exclude-filters)

Filters are split by context: `http`, `artisan`, and `jobs`.

```
'include' => [
    'http' => ['GET /api/*', 'POST /checkout', 'admin.users.*'],
    'artisan' => ['migrate*', 'app:*'],
    'jobs' => ['App\\Jobs\\Important*'],
],

'exclude' => [
    'http' => [
        '/up',
        '/sanctum/csrf-cookie',
        '/telescope',
        '/telescope/*',
        '/horizon',
        '/horizon/*',
        '/pulse',
        '/pulse/*',
        '/livewire',
        '/livewire/*',
        '/_ignition',
        '/_ignition/*',
        'OPTIONS *',
        'GET /health*',
    ],
    'artisan' => ['queue:work', 'horizon:*'],
    'jobs' => ['App\\Jobs\\NoisyDebugJob'],
],
```

Supported filter styles:

- Wildcards like `GET /api/*`
- Route names like `admin.users.*`
- Regex patterns like `/^POST \/checkout/`
- Command patterns like `queue:*`
- Job class patterns like `App\\Jobs\\*`
- Controller or action strings matched through Laravel's string matcher

The published config excludes common Laravel framework-noise routes by default: `/up`, `/sanctum/csrf-cookie`, `telescope/*`, `horizon/*`, `pulse/*`, `livewire/*`, `/_ignition/*`, and all `OPTIONS` requests. Remove any of those entries from `exclude.http` if you want to profile them.

How it behaves
--------------

[](#how-it-behaves)

### HTTP requests

[](#http-requests)

`PerfbaseMiddleware` creates an `HttpTraceLifecycle` for the current request.

By default, only HTTP responses with a status code in `profile_http_status_codes` are submitted. The published config ships with `[...range(200, 299), ...range(500, 599)]`.

HTTP include/exclude filters can match Laravel route names as well as URIs and controller/action strings.

Recorded attributes include:

- `source=http`
- `action`
- `http_method`
- `http_url`
- `http_status_code`
- `user_ip`
- `user_agent`
- `user_id` when available
- `environment`
- `app_version`
- `hostname`
- `php_version`

### Artisan commands

[](#artisan-commands)

The service provider listens to Laravel console events and creates a `ConsoleTraceLifecycle`.

Recorded attributes include:

- `source=artisan`
- `action`
- `exit_code`
- `exception` when present
- `environment`
- `app_version`
- `hostname`
- `php_version`

### Queue jobs

[](#queue-jobs)

The service provider listens to queue worker events and creates a `QueueTraceLifecycle`.

Recorded attributes include:

- `source=jobs`
- `action`
- `queue`
- `connection`
- `exception` when present
- `environment`
- `app_version`
- `hostname`
- `php_version`

Manual spans
------------

[](#manual-spans)

Use the facade when you want custom spans inside your own application code:

```
use Perfbase\Laravel\Facades\Perfbase;

Perfbase::startTraceSpan('custom-operation', [
    'operation_type' => 'data_processing',
    'record_count' => '1000',
]);

Perfbase::setAttribute('processing_method', 'batch');
Perfbase::setAttribute('memory_usage', (string) memory_get_usage());

try {
    processLargeDataset();
    Perfbase::setAttribute('status', 'success');
} catch (\Exception $e) {
    Perfbase::setAttribute('status', 'error');
    Perfbase::setAttribute('error_message', $e->getMessage());
    throw $e;
} finally {
    Perfbase::stopTraceSpan('custom-operation');
}

$result = Perfbase::submitTrace();

if (!$result->isSuccess()) {
    logger()->warning('Perfbase trace submission failed', [
        'status' => $result->getStatus(),
        'message' => $result->getMessage(),
        'status_code' => $result->getStatusCode(),
    ]);
}
```

Note that Perfbase trace attributes are string values. Cast integers and booleans before passing them to `setAttribute()`.

Dependency injection
--------------------

[](#dependency-injection)

You can inject the SDK client directly:

```
use Perfbase\SDK\Perfbase;

class DataProcessingService
{
    /** @var Perfbase */
    private $perfbase;

    public function __construct(Perfbase $perfbase)
    {
        $this->perfbase = $perfbase;
    }

    public function processData(array $data): array
    {
        $this->perfbase->startTraceSpan('data-processing', [
            'record_count' => (string) count($data),
            'data_type' => 'user_records',
        ]);

        try {
            $result = $this->performProcessing($data);
            $this->perfbase->setAttribute('processed_count', (string) count($result));
            return $result;
        } finally {
            $this->perfbase->stopTraceSpan('data-processing');
        }
    }
}
```

User-specific request profiling
-------------------------------

[](#user-specific-request-profiling)

If your authenticated user model implements `Perfbase\Laravel\Interfaces\ProfiledUser`, HTTP request profiling will respect `shouldBeProfiled()`.

```
use Perfbase\Laravel\Interfaces\ProfiledUser;

class User extends Authenticatable implements ProfiledUser
{
    public function shouldBeProfiled(): bool
    {
        return $this->isAdmin() || $this->isBetaTester();
    }
}
```

If the authenticated user does not implement `ProfiledUser`, the package falls back to normal request filtering rules.

Facade methods
--------------

[](#facade-methods)

MethodDescription`startTraceSpan($name, $attributes = [])`Start a named span`stopTraceSpan($name)`Stop a named span`setAttribute($key, $value)`Add a string attribute to the current trace`setFlags($flags)`Change extension feature flags`submitTrace()`Submit trace data and return a `SubmitResult``getTraceData($spanName = '')`Get raw trace data`reset()`Clear the current trace session`isExtensionAvailable()`Check whether the native extension is loadedError handling
--------------

[](#error-handling)

The package is designed to fail open in normal operation. When profiling cannot start or trace submission fails, your Laravel request, command, or job should continue running.

Use `PERFBASE_DEBUG=true` if you want profiling exceptions to surface during local development.

Testing
-------

[](#testing)

In application tests, it is often simplest to disable profiling:

```

```

You can also mock the facade:

```
use Perfbase\Laravel\Facades\Perfbase;

public function test_something()
{
    Perfbase::shouldReceive('startTraceSpan')->once();
    Perfbase::shouldReceive('stopTraceSpan')->once();

    // ...
}
```

Troubleshooting
---------------

[](#troubleshooting)

### Extension not loaded

[](#extension-not-loaded)

```
php -m | grep perfbase
php --ini
bash -c "$(curl -fsSL https://cdn.perfbase.com/install.sh)"
```

### High overhead

[](#high-overhead)

- Lower `PERFBASE_SAMPLE_RATE`
- Use `FeatureFlags::UseCoarseClock`
- Disable feature flags you do not need
- Narrow your `include` filters and expand your `exclude` filters

Documentation
-------------

[](#documentation)

Full documentation is available at [perfbase.com/docs](https://perfbase.com/docs).

- **Docs**: [perfbase.com/docs](https://perfbase.com/docs)
- **Issues**: [github.com/perfbaseorg/laravel/issues](https://github.com/perfbaseorg/laravel/issues)
- **Support**:

License
-------

[](#license)

Apache-2.0. See [LICENSE.txt](LICENSE.txt).

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance86

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~24 days

Recently: every ~4 days

Total

23

Last Release

69d ago

Major Versions

v0.3.0 → v1.0.02026-04-08

PHP version history (3 changes)0.0.1PHP ^8.0|^8.1|^8.2|^8.3|^8.4

0.0.2PHP &gt;=7.4 &lt;8.5

v1.2.0PHP &gt;=7.4 &lt;8.6

### Community

Maintainers

![](https://www.gravatar.com/avatar/85d93938cbda24f3ae1b325d2c1ac89e95f1f845365395a693bad51e8b61b5d9?d=identicon)[BenPoulson](/maintainers/BenPoulson)

---

Top Contributors

[![benpoulson](https://avatars.githubusercontent.com/u/1797843?v=4)](https://github.com/benpoulson "benpoulson (75 commits)")

---

Tags

apmlaravelperformancephplaravelprofilingPerfbase

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/perfbase-laravel/health.svg)

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

###  Alternatives

[laravel/socialite

Laravel wrapper around OAuth 1 &amp; OAuth 2 libraries.

5.7k108.5M889](/packages/laravel-socialite)[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[laravel/boost

Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.

3.5k21.5M603](/packages/laravel-boost)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M167](/packages/spatie-laravel-health)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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