Using Blackfire’s PHP SDK to profile a Laravel app.
1 min readJun 2, 2025
Install the package:
#https://github.com/blackfireio/php-sdk
composer require blackfire/php-sdk
after install, create a middleware and add register that middleware and apply into the desired routes
'blackfire' => \App\Http\Middleware\BlackfireProfiler::class,
<?php
namespace App\Http\Middleware;
use Blackfire\ClientConfiguration;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Blackfire\Client;
use Blackfire\Profile\Configuration;
class BlackfireProfiler
{
public function handle(Request $request, Closure $next): Response
{
$currentPath = trim($request->path(), '/');
if (!filter_var(config('services.blackfire.enabled'), FILTER_VALIDATE_BOOLEAN)) {
return $next($request);
}
if (!config('services.blackfire.client_id') || !config('services.blackfire.client_token')) {
return $next($request);
}
$probe = null;
$blackfire = null;
try {
$ClientConfig = new ClientConfiguration(config('services.blackfire.client_id'), config('services.blackfire.client_token'), config('services.blackfire.environment'));
$blackfire = new Client($ClientConfig);
$config = new \Blackfire\Profile\Configuration();
$config->setTitle('Profile SDK for: ' . $currentPath);
$config->setMetadata('full-url', $request->fullUrl());
$probe = $blackfire->createProbe($config);
} catch (\Exception $e) {
\Log::error($e);
}
$response = $next($request);
try {
if ($blackfire && $probe) {
$blackfire->endProbe($probe);
}
} catch (\Exception $e) {
\Log::error($e);
}
return $response;
}
}