Skip to main content
Integrations

Laravel Integration

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

Installation

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

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

Then install the Laravel package:

composer require perfbase/laravel

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

Configuration

Add to your .env:

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

Publish the config file for full control:

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

Environment variables

VariableDefaultDescription
PERFBASE_ENABLEDfalseMaster on/off switch for all profiling.
PERFBASE_API_KEY-Your project API key. Required.
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.

HTTP middleware

Add PerfbaseMiddleware to your middleware stack to profile HTTP requests:

// Laravel 11+ (bootstrap/app.php)
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Perfbase\Laravel\Middleware\PerfbaseMiddleware::class);
})

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

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

'include' => [
    'http' => ['*'],                          // Profile all routes (default)
],
'exclude' => [
    'http' => ['health', 'telescope/*'],      // Skip these
],

Pattern types

  • 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/*.

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' => [
    'queue' => ['*'],                              // All jobs (default)
],
'exclude' => [
    'queue' => ['App\\Jobs\\Heartbeat'],           // Skip specific jobs
],

Each job gets its own trace with the span name queue.{ClassName} (e.g., queue.ProcessEmail). Queue name and connection are recorded as attributes.

Artisan command profiling

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

'include' => [
    'console' => ['*'],                            // All commands (default)
],
'exclude' => [
    'console' => ['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 a span named console.{command} (e.g., console.migrate). 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, console, or queue
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 (HTTP only)
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, the request is skipped entirely, with no profiling overhead. This check applies to HTTP requests only.

Sample rate

The sample rate controls what fraction of requests 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 request isn’t sampled, no profiling overhead is incurred.

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.