Skip to main content
Integrations

Laravel Integration

The Perfbase Laravel package provides automatic profiling for HTTP requests, jobs, and Artisan commands. Supports Laravel 8 through 13 on PHP 7.4 through 8.5.

Installation

1. Install the Perfbase PHP extension

Install the extension first. This is what does the actual profiling:

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.

2. Install the Laravel integration

Install the Laravel package with Composer:

composer require perfbase/laravel:^1.0

The service provider is auto-discovered. No manual registration needed.

3. Publish config/perfbase.php

Publish the config file so your app owns the Perfbase defaults:

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

4. Add the HTTP middleware

HTTP profiling is enabled only when PerfbaseMiddleware is present. Queue jobs and Artisan commands are wired through the package service provider and do not need this middleware.

For Laravel 11+, add the import lines at the top of bootstrap/app.php, then append the middleware inside withMiddleware():

// bootstrap/app.php
use Illuminate\Foundation\Configuration\Middleware;
use Perfbase\Laravel\Middleware\PerfbaseMiddleware;

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(PerfbaseMiddleware::class);
});

For Laravel 8-10, add it to the global middleware stack in app/Http/Kernel.php:

// app/Http/Kernel.php
protected $middleware = [
    // ...
    \Perfbase\Laravel\Middleware\PerfbaseMiddleware::class,
];

Or attach it only to a middleware group:

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

Configuration

Add to your .env after creating the project API key:

PERFBASE_ENABLED=true
PERFBASE_API_KEY=your-project-api-key
PERFBASE_SAMPLE_RATE=0.1

Environment variables

VariableDefaultDescription
PERFBASE_ENABLEDfalseMaster on/off switch for all profiling.
PERFBASE_API_KEY-Your project API key. Required.
PERFBASE_API_URLhttps://ingress.perfbase.cloudIngestion endpoint.
PERFBASE_SAMPLE_RATE0.1Fraction of requests to profile (0.0–1.0). 0.1 = 10%.
PERFBASE_TIMEOUT5HTTP timeout in seconds for trace submission.
PERFBASE_PROXY-Optional proxy URL (http, https, socks5, socks5h).
PERFBASE_FLAGSDefaultFlagsSDK feature flags bitmask. See Feature flags.
PERFBASE_DEBUGfalseWhen true, profiling errors are thrown instead of silently logged.
PERFBASE_LOG_ERRORStrueLog profiling errors via Laravel’s logger.

Control which routes are profiled with include/exclude patterns in config/perfbase.php:

'include' => [
    'http' => ['.*'],                         // Match all routes (default)
],
'exclude' => [
    'http' => ['/up', '/telescope/*', '/horizon/*', 'OPTIONS *'],
],

Pattern types

  • Match all: ['.*'] or ['*']
  • Wildcards: api/*, admin/users/* (uses Laravel’s Str::is())
  • Regex: /^POST \/api\// (wrapped in forward slashes)
  • Controller references: UserController@show, App\Http\Controllers\UserController
  • Method + path: POST /api/users, GET /dashboard

Patterns are matched against the request method, path, route URI, and controller action, so UserController@show works just as well as GET /users/*.

HTTP traces are submitted only for status codes listed in profile_http_status_codes in config/perfbase.php. The default keeps 2xx and 5xx responses and drops 4xx responses such as 404 unless you add them.

Queue profiling

Queue jobs are profiled automatically via event listeners. No middleware is required. The service provider listens for JobProcessing, JobProcessed, and JobExceptionOccurred events.

Configure which jobs to profile:

'include' => [
    'jobs' => ['.*'],                              // Match all jobs (default)
],
'exclude' => [
    'jobs' => ['App\\Jobs\\Heartbeat'],            // Skip specific jobs
],

Each job gets its own trace with the span name queue. The job class is recorded in the action attribute, and the queue name and connection are recorded as attributes.

Artisan command profiling

Artisan commands are profiled automatically via CommandStarting and CommandFinished event listeners.

'include' => [
    'artisan' => ['.*'],                           // Match all commands (default)
],
'exclude' => [
    'artisan' => ['queue:work'],                   // Excluded by default
],

The queue:work command is excluded by default to avoid profiling the long-running worker process itself (individual jobs are profiled separately via queue profiling).

Each command gets the span name artisan. The command name is recorded in the action attribute, and the exit code is recorded as an attribute.

Custom attributes

Add context to your traces anywhere in your application:

use Perfbase\Laravel\Facades\Perfbase;

Perfbase::setAttribute('user_id', (string) auth()->id());
Perfbase::setAttribute('tenant', $tenant->slug);

The package automatically sets these attributes on every trace:

AttributeSource
hostnamegethostname()
environmentapp.env config value
app_versionapp.version config value
php_versionPHP version
sourcehttp, artisan, or jobs
actionRoute path, command name, or job class
http_methodRequest method (HTTP only)
http_urlFull request URL (HTTP only)
http_status_codeResponse status code (HTTP only)
user_ipClient IP address for HTTP traces; server IP for non-HTTP traces
user_agentUser agent string (HTTP only)
user_idAuthenticated user ID, if present (HTTP only)

Per-user profiling control

Implement the ProfiledUser interface on your User model to control profiling per user:

use Perfbase\Laravel\Interfaces\ProfiledUser;

class User extends Authenticatable implements ProfiledUser
{
    public function shouldBeProfiled(): bool
    {
        return !$this->is_admin;
    }
}

When a user returns false, no extension trace span is started for that request. This check applies to HTTP requests only.

Sample rate

The sample rate controls what fraction of requests, jobs, and Artisan commands are profiled. The default is 0.1 (10%):

PERFBASE_SAMPLE_RATE=1.0   # Profile everything (development)
PERFBASE_SAMPLE_RATE=0.1   # 10% of requests (production)
PERFBASE_SAMPLE_RATE=0.01  # 1% of requests (high-traffic)

The check happens early. If a unit of work is not sampled, no extension trace span is started.

Error handling

Profiling never crashes your application. In production (PERFBASE_DEBUG=false), all profiling errors are caught and optionally logged. In development (PERFBASE_DEBUG=true), errors are thrown so you can catch configuration issues early.

Using the Facade

The Perfbase facade proxies to the SDK singleton, so you can use it for manual profiling alongside the automatic middleware:

use Perfbase\Laravel\Facades\Perfbase;

Perfbase::startTraceSpan('custom-operation');
// ... do work ...
Perfbase::stopTraceSpan('custom-operation');
Perfbase::submitTrace();

See the PHP SDK docs for the full API reference.