Laravel Debugbar shows queries, timings and your own debug messages in a bar at the bottom of the browser. Here is how to set it up and use it.
Introduction
Laravel Debugbar, created by Barry vd. Heuvel, is a debugging tool for Laravel. Unlike dd() or dump(), which halt the script, Debugbar lets you inspect the app while the request runs to the end.
Installation and Configuration
Install Laravel Debugbar as a dev dependency:
composer require fruitcake/laravel-debugbar --dev
The package was formerly published as barryvdh/laravel-debugbar; version 4 moved to fruitcake/laravel-debugbar (namespace Fruitcake\LaravelDebugbar). It is auto-discovered, so no manual registration is needed. Only if you disabled package discovery, add the ServiceProvider to your config/app.php:
Fruitcake\LaravelDebugbar\ServiceProvider::class,
and optionally the alias:
'Debugbar' => Fruitcake\LaravelDebugbar\Facades\Debugbar::class,
Then publish the configuration file:
php artisan vendor:publish --provider="Fruitcake\LaravelDebugbar\ServiceProvider"
By default Debugbar is enabled when APP_DEBUG is true (the enabled option in config/debugbar.php is null, overridable with DEBUGBAR_ENABLED). It is a development tool: keep APP_DEBUG=false in production.
Non-invasive Debugging with Debugbar::addMessage()
Debugbar lets you add messages without halting the script:
use Debugbar;
public function show($id)
{
$user = User::find($id);
// Instead of dd($user) or dump($user)
Debugbar::info($user);
// We can also add custom messages
Debugbar::addMessage('User has been retrieved', 'info');
// Note that the application continues running
return view('users.show', compact('user'));
}
Message types are color-coded in the interface:
Debugbar::info($variable); // Information
Debugbar::error($variable); // Error
Debugbar::warning($variable); // Warning
Debugbar::addMessage($variable, 'debug'); // Debug
You can also log arrays, collections and objects:
$users = User::with('posts')->get();
Debugbar::info($users);
Nested structures can be expanded in the bar.
Performance Measurement with Debugbar::startMeasure()
Debugbar can also time specific code blocks:
Debugbar::startMeasure('render', 'View rendering time');
// Some complex code we want to measure
$view = view('complex.view', $data)->render();
Debugbar::stopMeasure('render');
Measurements can be nested to locate slow segments:
Debugbar::startMeasure('total', 'Total processing time');
Debugbar::startMeasure('database', 'Database operations');
$posts = Post::with('comments', 'author', 'categories')->get();
Debugbar::stopMeasure('database');
Debugbar::startMeasure('transform', 'Data transformation');
$transformedData = $this->transformService->transformPosts($posts);
Debugbar::stopMeasure('transform');
Debugbar::startMeasure('render', 'View rendering');
$view = view('posts.index', compact('transformedData'))->render();
Debugbar::stopMeasure('render');
Debugbar::stopMeasure('total');
return $view;
SQL Query Tracking
Laravel Debugbar automatically tracks all SQL queries executed during request processing. Add your own messages to the Messages tab to mark where something happens:
// Queries are collected automatically; a message marks the spot in the timeline
Debugbar::info('Fetching active users');
$activeUsers = User::where('status', 'active')->get();
Debugbar shows not only the queries themselves but also their execution time, parameters, and the location in code from where they were called.
API and Ajax Debugging
Debugbar injects itself into HTML responses; Ajax and JSON requests are captured when capture_ajax is enabled (the default in version 4):
// In config/debugbar.php configuration file:
'capture_ajax' => env('DEBUGBAR_CAPTURE_AJAX', true),
For API requests, the same helpers work:
public function apiEndpoint()
{
$data = $this->processData();
// API logging
Debugbar::debug('API called with parameters: ' . json_encode(request()->all()));
// Add data to a separate tab in Debugbar
Debugbar::addMessage($data, 'api_data');
return response()->json($data);
}
Ajax requests made from the page look like this:
// Ajax responses are captured automatically when capture_ajax is on:
// the request shows up in the request selector of the bar
$.ajax({
url: '/api/data',
success: function (data) {
console.log(data);
}
});
Custom Data Collections
You can add your own tab to the bar with a custom data collector:
use DebugBar\DataCollector\DataCollector;
use DebugBar\DataCollector\Renderable;
class MyCustomCollector extends DataCollector implements Renderable
{
protected $data = [];
public function addData($key, $value)
{
$this->data[$key] = $value;
}
public function collect(): array
{
return $this->data;
}
public function getName(): string
{
return 'custom';
}
public function getWidgets(): array
{
return [
"custom" => [
"icon" => "cubes",
"widget" => "PhpDebugBar.Widgets.VariableListWidget",
"map" => "custom",
"default" => "{}"
]
];
}
}
// Register collector
$customCollector = new MyCustomCollector();
Debugbar::addCollector($customCollector);
// Add data
$customCollector->addData('key1', 'value1');
$customCollector->addData('key2', ['nested' => 'array']);
Debugging in Tests
Debugbar also works in tests, for example to find out why one is slow:
public function testSlowOperation()
{
Debugbar::enable(); // Enable Debugbar in this test
Debugbar::startMeasure('slow_test', 'Slow test');
// Test code
$result = $this->service->performComplexOperation();
Debugbar::stopMeasure('slow_test');
// Save debug report to file
$debugbarData = Debugbar::getData();
file_put_contents(
storage_path('logs/test_debug_' . time() . '.json'),
json_encode($debugbarData)
);
$this->assertTrue($result);
}
You can then analyze the saved data to identify slow code segments.
Practical Examples
Example 1: Debugging N+1 Query Problems
public function index()
{
Debugbar::startMeasure('posts_query', 'Fetching posts');
// N+1 query problem
$posts = Post::all();
Debugbar::info('Number of posts: ' . count($posts));
Debugbar::stopMeasure('posts_query');
foreach ($posts as $post) {
// Each of these calls will generate an additional query - Debugbar will show them all
$post->author->name;
}
// Solution
Debugbar::startMeasure('posts_eager', 'Fetching posts with eager loading');
$optimizedPosts = Post::with('author')->get();
Debugbar::stopMeasure('posts_eager');
return view('posts.index', compact('optimizedPosts'));
}
Example 2: Memory Usage Debugging
public function processLargeDataset()
{
Debugbar::startMeasure('memory_test', 'Memory usage test');
$initialMemory = memory_get_usage();
Debugbar::info('Initial memory usage: ' . $this->formatBytes($initialMemory));
// Memory-intensive operation
$data = $this->largeDataService->processData();
$afterMemory = memory_get_usage();
Debugbar::info('Final memory usage: ' . $this->formatBytes($afterMemory));
Debugbar::info('Difference: ' . $this->formatBytes($afterMemory - $initialMemory));
Debugbar::stopMeasure('memory_test');
return response()->json(['status' => 'completed']);
}
private function formatBytes($bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
Example 3: Debugging Multi-threaded Processes
public function runQueue()
{
Debugbar::startMeasure('queue_process', 'Queue processing');
dispatch(function () {
// This won't be visible in Debugbar as it runs in a separate queue worker process (queues, not threads)
logger('Job started');
});
// Solution: save job ID and monitor its status
$jobId = Str::uuid();
Debugbar::info('Job with ID: ' . $jobId . ' has been queued');
dispatch(function () use ($jobId) {
cache()->put('job_status_' . $jobId, 'running', now()->addMinutes(5));
// Processing
cache()->put('job_status_' . $jobId, 'completed', now()->addMinutes(5));
});
// In a real application, we would use AJAX to check status
Debugbar::info('Job status can be checked via cache()->get("job_status_' . $jobId . '")');
Debugbar::stopMeasure('queue_process');
return response()->json(['job_id' => $jobId]);
}
Summary
Install it with --dev, keep it enabled only in local, and start with the queries tab and startMeasure().