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.

v0.3.0(10mo ago)0910Apache-2.0PHPPHP &gt;=7.4 &lt;8.5CI passing

Since Nov 7Pushed 10mo 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 1mo ago

READMEChangelog (10)Dependencies (7)Versions (18)Used By (0)

Perfbase for Laravel
====================

[](#perfbase-for-laravel)

[![Packagist License](https://camo.githubusercontent.com/4ae0be02d71c1ae0a1134e7463bbc6d076c872cece6c4c32458af10518fad835/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f70657266626173652f6c61726176656c)](https://github.com/perfbaseorg/laravel/blob/main/LICENSE.txt)[![Packagist Version](https://camo.githubusercontent.com/dd414beeacf08d31e374eb36db47990401ce9b1fd24610afaa4e2b529b7afcc9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70657266626173652f6c61726176656c)](https://packagist.org/packages/perfbase/laravel)[![GitHub Actions Workflow Status](https://camo.githubusercontent.com/bd58728f8d7ae43b103937b72b952d0b5a36a793e3bb563a5cba8db50fccbe2f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70657266626173656f72672f6c61726176656c2f63692e796d6c3f6272616e63683d6d61696e)](https://github.com/perfbaseorg/laravel/actions/workflows/ci.yml)

Seamless Laravel integration for Perfbase - a comprehensive Application Performance Monitoring (APM) solution that provides real-time insights into your Laravel application's performance, database queries, HTTP requests, queue jobs, and more.

Features
--------

[](#features)

- 🚀 **Automatic Profiling** - HTTP requests, console commands, and queue jobs
- 📊 **Multi-span Tracing** - Track nested operations within requests
- 🔍 **Database Query Monitoring** - Monitor all database operations with timing
- 🌐 **HTTP Request Tracking** - Monitor outbound API calls and their performance
- ⚡ **Queue Job Profiling** - Track background job performance and failures
- 🏷️ **Custom Attributes** - Add contextual metadata to traces
- 🎯 **Smart Sampling** - Control data collection with configurable sample rates
- 💾 **Flexible Data Storage** - Sync immediately or buffer locally (file/database)
- 🔧 **Granular Control** - Include/exclude specific routes, commands, or jobs
- 🛡️ **Multi-tenant Support** - Organization and project-level data isolation

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

[](#requirements)

- **PHP**: 7.4 to 8.4
- **Laravel**: 8.0, 9.0, 10.0, 11.0, or 12.0
- **Extensions**:
    - `ext-json` (usually enabled by default)
    - `ext-zlib` (usually enabled by default)
    - `ext-perfbase` (Perfbase PHP extension)
- **Dependencies**: Guzzle HTTP 7.0+

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

[](#installation)

### 1. Install the Package

[](#1-install-the-package)

```
composer require perfbase/laravel
```

### 2. Install the Perfbase PHP Extension

[](#2-install-the-perfbase-php-extension)

The `ext-perfbase` PHP extension is required. Install it using:

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

**Important**: Restart your web server after installation.

### 3. Publish Configuration

[](#3-publish-configuration)

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

This creates `config/perfbase.php` with all available options.

### 4. Configure Environment

[](#4-configure-environment)

Add to your `.env` file:

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

### 5. Add Middleware (Optional but Recommended)

[](#5-add-middleware-optional-but-recommended)

For HTTP request profiling, add the middleware to your HTTP kernel:

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

Or apply to specific route groups:

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

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

[](#configuration)

### Basic Configuration

[](#basic-configuration)

The package auto-registers and provides several configuration options:

```
// config/perfbase.php
return [
    'enabled' => env('PERFBASE_ENABLED', false),
    'api_key' => env('PERFBASE_API_KEY'),
    'sample_rate' => env('PERFBASE_SAMPLE_RATE', 0.1),

    'sending' => [
        'mode' => env('PERFBASE_SENDING_MODE', 'sync'),
        'timeout' => env('PERFBASE_TIMEOUT', 5),
        'proxy' => env('PERFBASE_PROXY'),
    ],

    'flags' => env('PERFBASE_FLAGS', \Perfbase\SDK\FeatureFlags::DefaultFlags),
    // ... more options
];
```

### Environment Variables

[](#environment-variables)

VariableDefaultDescription`PERFBASE_ENABLED``false`Enable/disable profiling`PERFBASE_API_KEY``null`Your Perfbase API key (required)`PERFBASE_SAMPLE_RATE``0.1`Sampling rate (0.0 to 1.0)`PERFBASE_SENDING_MODE``sync`Data sending mode (`sync`, `file`, `database`)`PERFBASE_TIMEOUT``5`API request timeout in seconds`PERFBASE_PROXY``null`HTTP proxy URL`PERFBASE_FLAGS`Default flagsProfiling feature flags### Sending Modes

[](#sending-modes)

#### Sync Mode (Default)

[](#sync-mode-default)

Data is sent immediately to Perfbase:

```
PERFBASE_SENDING_MODE=sync
```

#### File Buffering

[](#file-buffering)

Data is stored in local files and sent later:

```
PERFBASE_SENDING_MODE=file
```

#### Database Buffering

[](#database-buffering)

Data is cached in your database and sent later:

```
PERFBASE_SENDING_MODE=database
```

### Profiling Features Control

[](#profiling-features-control)

Control which profiling features are enabled:

```
use Perfbase\SDK\FeatureFlags;

// In config/perfbase.php
'flags' => FeatureFlags::DefaultFlags, // Recommended for most apps
'flags' => FeatureFlags::AllFlags,     // All available features
'flags' => FeatureFlags::TrackCpuTime | FeatureFlags::TrackPdo, // Custom combination
```

Available flags:

- `UseCoarseClock` - Faster timing (reduced overhead)
- `TrackCpuTime` - Monitor CPU time usage
- `TrackMemoryAllocation` - Track memory allocation patterns
- `TrackPdo` - Monitor database queries
- `TrackHttp` - Track outbound HTTP requests
- `TrackCaches` - Monitor cache operations
- `TrackMongodb` - Track MongoDB operations
- `TrackElasticsearch` - Monitor Elasticsearch queries
- `TrackQueues` - Track queue/background jobs
- `TrackAwsSdk` - Monitor AWS SDK operations
- `TrackFileOperations` - Track file I/O operations

### Include/Exclude Filters

[](#includeexclude-filters)

Control which routes, commands, and jobs are profiled:

```
// config/perfbase.php
'include' => [
    'http' => [
        'api/*',
        'admin/*'
    ],
    'console' => [
        'app:*',
        'queue:*'
    ],
    'queue' => [
        'App\\Jobs\\*'
    ]
],

'exclude' => [
    'http' => [
        'health-check',
        '_debugbar/*'
    ],
    'console' => [
        'horizon:*',
        'telescope:*'
    ],
    'queue' => [
        'App\\Jobs\\DebugJob'
    ]
]
```

Usage
-----

[](#usage)

### Automatic Profiling

[](#automatic-profiling)

Once configured, Perfbase automatically profiles:

- **HTTP Requests** (when middleware is added)
- **Console Commands** (all artisan commands)
- **Queue Jobs** (all queued jobs)

### Manual Profiling

[](#manual-profiling)

Use the facade for custom profiling:

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

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

// Add attributes during execution
Perfbase::setAttribute('processing_method', 'batch');
Perfbase::setAttribute('memory_usage', memory_get_usage());

try {
    // Your custom logic here
    processLargeDataset();

    Perfbase::setAttribute('status', 'success');
} catch (Exception $e) {
    Perfbase::setAttribute('status', 'error');
    Perfbase::setAttribute('error_message', $e->getMessage());
} finally {
    // Always stop the span
    Perfbase::stopTraceSpan('custom-operation');
}

// Submit the trace data
Perfbase::submitTrace();
```

### Service Injection

[](#service-injection)

Use dependency injection in your services:

```
use Perfbase\SDK\Perfbase;

class DataProcessingService
{
    public function __construct(private Perfbase $perfbase)
    {
    }

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

        $result = $this->performProcessing($data);

        $this->perfbase->setAttribute('processed_count', count($result));
        $this->perfbase->stopTraceSpan('data-processing');

        return $result;
    }
}
```

### User-Specific Profiling

[](#user-specific-profiling)

Profile specific users by implementing the `ProfiledUser` interface:

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

class User extends Authenticatable implements ProfiledUser
{
    public function shouldBeProfiled(): bool
    {
        // Profile admin users or users in beta testing
        return $this->isAdmin() || $this->isBetaTester();
    }
}
```

Artisan Commands
----------------

[](#artisan-commands)

### Sync Buffered Data

[](#sync-buffered-data)

When using `file` or `database` sending modes, use this command to send buffered data:

```
# Send all buffered trace data to Perfbase
php artisan perfbase:sync

# Recommended: Set up a cron job
# * * * * * cd /path-to-your-project && php artisan perfbase:sync >> /dev/null 2>&1
```

### Clear Buffered Data

[](#clear-buffered-data)

Remove all locally buffered traces:

```
# Clear all buffered data (useful for debugging)
php artisan perfbase:clear
```

Advanced Configuration
----------------------

[](#advanced-configuration)

### Database Strategy Setup

[](#database-strategy-setup)

When using `database` sending mode, you may need to run the migration:

```
php artisan migrate
```

The package includes a migration for the `perfbase_profiles` table.

### Custom Cache Paths

[](#custom-cache-paths)

For file-based buffering, customize the storage path:

```
// config/perfbase.php
'sending' => [
    'mode' => 'file',
    'config' => [
        'file' => [
            'path' => storage_path('app/perfbase-cache'),
        ],
    ],
],
```

### Performance Optimization

[](#performance-optimization)

For high-traffic applications:

```
// config/perfbase.php
'sample_rate' => 0.01, // Profile 1% of requests
'flags' => \Perfbase\SDK\FeatureFlags::UseCoarseClock |
           \Perfbase\SDK\FeatureFlags::TrackCpuTime |
           \Perfbase\SDK\FeatureFlags::TrackPdo,
'sending' => ['mode' => 'file'], // Buffer locally
```

### Multi-Environment Setup

[](#multi-environment-setup)

```
// config/perfbase.php
'enabled' => env('PERFBASE_ENABLED', app()->environment('production')),
'sample_rate' => env('PERFBASE_SAMPLE_RATE', match(app()->environment()) {
    'production' => 0.1,
    'staging' => 0.5,
    'local' => 1.0,
    default => 0.1
}),
```

Facade Methods
--------------

[](#facade-methods)

The Perfbase facade provides access to all SDK methods:

MethodDescription`startTraceSpan($name, $attributes = [])`Start profiling a named span`stopTraceSpan($name)`Stop profiling a named span`setAttribute($key, $value)`Add attribute to current trace`setFlags($flags)`Change profiling feature flags`submitTrace()`Submit trace data to Perfbase`getTraceData($spanName = '')`Get raw trace data`reset()`Clear current trace session`isExtensionAvailable()`Check if extension is loadedError Handling
--------------

[](#error-handling)

The package handles errors gracefully:

```
// The package won't break your app if Perfbase is unavailable
try {
    Perfbase::startTraceSpan('critical-operation');
    // Your code here
} catch (\Perfbase\SDK\Exception\PerfbaseExtensionException $e) {
    // Extension not available - log but continue
    Log::warning('Perfbase extension not available: ' . $e->getMessage());
}
```

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

[](#troubleshooting)

### Extension Not Found

[](#extension-not-found)

```
# Check if extension is loaded
php -m | grep perfbase

# Check PHP configuration
php --ini

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

### Permission Issues (File Mode)

[](#permission-issues-file-mode)

```
# Ensure storage directory is writable
chmod -R 755 storage/perfbase
chown -R www-data:www-data storage/perfbase
```

### High Memory Usage

[](#high-memory-usage)

```
// Reduce profiling overhead
'flags' => \Perfbase\SDK\FeatureFlags::UseCoarseClock |
           \Perfbase\SDK\FeatureFlags::TrackCpuTime,
'sample_rate' => 0.01, // Lower sample rate
```

### Database Issues (Database Mode)

[](#database-issues-database-mode)

```
# Ensure migration is run
php artisan migrate

# Check database connection
php artisan tinker
>>> DB::connection()->getPdo();
```

Testing
-------

[](#testing)

When testing your Laravel application:

```
// Disable Perfbase in tests
// phpunit.xml

// Or mock the facade in tests
public function test_something()
{
    Perfbase::shouldReceive('startTraceSpan')->once();
    Perfbase::shouldReceive('stopTraceSpan')->once();

    // Your test code
}
```

Performance Impact
------------------

[](#performance-impact)

- **Minimal Overhead**: ~1-3ms per request with default settings
- **Sampling**: Use sample rates to reduce impact in production
- **Async Options**: File/database modes reduce request impact
- **Selective Profiling**: Use include/exclude filters strategically

Security Considerations
-----------------------

[](#security-considerations)

- **API Key Security**: Store API keys in environment variables, not code
- **Data Privacy**: Configure include/exclude filters to avoid sensitive routes
- **User Profiling**: Implement `ProfiledUser` interface to control user-specific profiling
- **Network Security**: Use HTTPS endpoints and configure proxy if needed

Examples
--------

[](#examples)

### E-commerce Checkout

[](#e-commerce-checkout)

```
class CheckoutController extends Controller
{
    public function process(Request $request)
    {
        Perfbase::startTraceSpan('checkout-process', [
            'user_id' => auth()->id(),
            'cart_items' => $request->items->count(),
            'payment_method' => $request->payment_method
        ]);

        try {
            $order = $this->createOrder($request);
            $payment = $this->processPayment($order);

            Perfbase::setAttribute('order_id', $order->id);
            Perfbase::setAttribute('payment_status', $payment->status);

            return response()->json(['order' => $order]);
        } finally {
            Perfbase::stopTraceSpan('checkout-process');
        }
    }
}
```

### Background Job Processing

[](#background-job-processing)

```
class ProcessEmailCampaignJob implements ShouldQueue
{
    public function handle()
    {
        // Automatic profiling happens via queue listener
        // But you can add custom spans for detailed tracking

        Perfbase::startTraceSpan('email-template-render');
        $template = $this->renderTemplate();
        Perfbase::stopTraceSpan('email-template-render');

        Perfbase::startTraceSpan('email-send-batch');
        $this->sendEmails($template);
        Perfbase::stopTraceSpan('email-send-batch');
    }
}
```

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

[](#documentation)

Comprehensive documentation is available at , including:

- Complete API reference
- Framework-specific guides
- Performance optimization tips
- Data privacy and security policies
- Troubleshooting guides

Contributing
------------

[](#contributing)

We welcome contributions! Please see our [contributing guidelines](CONTRIBUTING.md) and feel free to submit pull requests.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Support
-------

[](#support)

- **Email**:
- **Documentation**:
- **Issues**: [GitHub Issues](https://github.com/perfbaseorg/laravel/issues)

License
-------

[](#license)

This project is licensed under the Apache License 2.0. Please see the [License File](LICENSE.txt) for more information.

---

**Made with ❤️ by the Perfbase team**

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance54

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 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 ~16 days

Recently: every ~22 days

Total

16

Last Release

313d ago

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

0.0.2PHP &gt;=7.4 &lt;8.5

### 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 (60 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

[barryvdh/laravel-debugbar

PHP Debugbar integration for Laravel

19.2k124.3M624](/packages/barryvdh-laravel-debugbar)[fruitcake/laravel-debugbar

PHP Debugbar integration for Laravel

19.1k662.9k29](/packages/fruitcake-laravel-debugbar)[spatie/laravel-ignition

A beautiful error page for Laravel applications.

573146.7M471](/packages/spatie-laravel-ignition)[glhd/laravel-dumper

382801.4k](/packages/glhd-laravel-dumper)[laracraft-tech/laravel-xhprof

Easy XHProf setup to profile your laravel application!

235321.4k](/packages/laracraft-tech-laravel-xhprof)[tzsk/sms

A robust and unified SMS gateway integration package for Laravel, supporting multiple providers.

320244.3k6](/packages/tzsk-sms)

PHPackages © 2026

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