Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Laravel Debugbar
https://github.com/fruitcake/laravel-debugbar
Admin
Laravel Debugbar is a debugging tool that integrates PHP Debug Bar with Laravel to display detailed
...
Tokens:
24,703
Snippets:
150
Trust Score:
8.1
Update:
1 month ago
Context
Skills
Chat
Benchmark
73.1
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Laravel Debugbar Laravel Debugbar is a PHP debugging and profiling package that integrates the PHP Debug Bar with Laravel applications. It provides a visual debug toolbar that displays comprehensive information about your application's runtime, including database queries, log messages, views, routes, exceptions, memory usage, and timing data. The package automatically injects itself into HTML responses and tracks AJAX/Livewire requests for seamless debugging during development. The package includes numerous data collectors that capture specific aspects of your application: QueryCollector shows all SQL queries with bindings and timing, ViewCollector displays loaded Blade templates, RouteCollector shows current route information, EventsCollector tracks all fired events, and many more. It supports multiple storage backends (file, Redis, PDO, SQLite) for persisting debug data across requests, enabling inspection of redirects, AJAX calls, and queued jobs. The toolbar supports both light and dark themes and integrates with popular code editors for one-click file opening. ## Installation Install the package using Composer as a development dependency and publish the configuration file to customize collectors and options. ```bash # Install Laravel Debugbar as a dev dependency composer require fruitcake/laravel-debugbar --dev # Publish the configuration file (optional) php artisan vendor:publish --provider="Fruitcake\LaravelDebugbar\ServiceProvider" ``` ## Enable/Disable Debugbar The Debugbar is automatically enabled when `APP_DEBUG=true`. Control it via environment variables or programmatically at runtime. ```php // Environment configuration (.env) APP_DEBUG=true DEBUGBAR_ENABLED=true // Runtime enable/disable use Fruitcake\LaravelDebugbar\Facades\Debugbar; // Enable debugbar programmatically Debugbar::enable(); // Disable debugbar programmatically Debugbar::disable(); // Or using the helper function debugbar()->enable(); debugbar()->disable(); ``` ## Logging Messages with PSR-3 Levels Add debug messages using the Debugbar facade with PSR-3 log levels (debug, info, notice, warning, error, critical, alert, emergency). ```php use Fruitcake\LaravelDebugbar\Facades\Debugbar; // Log different message types Debugbar::info($user); // Info level message with object Debugbar::debug('Processing started'); // Debug level message Debugbar::warning('Cache miss detected'); // Warning level message Debugbar::error('Failed to connect'); // Error level message // Add message with custom label Debugbar::addMessage('Custom data', 'mylabel'); Debugbar::addMessage(['key' => 'value'], 'api-response'); // Log multiple values at once Debugbar::info($request, $user, $config); ``` ## Debug Helper Function Use the global `debug()` helper function to quickly dump variables to the Messages collector without importing the facade. ```php // Debug single variable debug($user); // Debug multiple variables at once debug($request, $response, $config); // Debug with Laravel collections (chainable) $users = User::where('active', true)->get(); $users->debug(); // Returns collection and dumps to debugbar // Equivalent to using the facade use Fruitcake\LaravelDebugbar\Facades\Debugbar; Debugbar::addMessage($user, 'debug'); ``` ## Performance Timing and Measurement Measure execution time of code blocks using start/stop measures or the measure closure helper. ```php use Fruitcake\LaravelDebugbar\Facades\Debugbar; // Start and stop a named measure Debugbar::startMeasure('render', 'Time for rendering'); // ... perform rendering operation ... Debugbar::stopMeasure('render'); // Add a measure with explicit start/end times Debugbar::addMeasure('bootstrap', LARAVEL_START, microtime(true)); // Measure a closure (recommended approach) $result = Debugbar::measure('My long operation', function() { // Perform expensive operation return expensiveCalculation(); }); // Using helper functions start_measure('api-call', 'External API request'); $response = Http::get('https://api.example.com/data'); stop_measure('api-call'); // Measure with closure helper $data = measure('Database sync', function() { return DB::table('records')->get(); }); ``` ## Exception and Error Logging Log exceptions and throwables to the Debugbar for inspection in the Exceptions tab. ```php use Fruitcake\LaravelDebugbar\Facades\Debugbar; // Log caught exceptions try { $result = riskyOperation(); } catch (Exception $e) { Debugbar::addThrowable($e); // Continue with fallback logic $result = fallbackOperation(); } // Log exception using alias method try { processPayment($order); } catch (PaymentException $e) { Debugbar::addException($e); throw $e; // Re-throw after logging } // Exceptions from response errors are automatically captured // when the response has an exception property ``` ## Adding Custom Data Collectors Extend the Debugbar with custom data collectors to track application-specific data. ```php use Fruitcake\LaravelDebugbar\Facades\Debugbar; use DebugBar\DataCollector\MessagesCollector; use DebugBar\DataCollector\DataCollector; // Add a built-in collector with custom name Debugbar::addCollector(new MessagesCollector('api_logs')); // Add collector via service container $debugbar = app('debugbar'); $debugbar->addCollector(new MessagesCollector('custom_messages')); // Create custom collector class class ApiMetricsCollector extends DataCollector implements Renderable { protected array $metrics = []; public function addMetric(string $name, float $value): void { $this->metrics[$name] = $value; } public function collect(): array { return ['metrics' => $this->metrics]; } public function getName(): string { return 'api_metrics'; } public function getWidgets(): array { return [ 'api_metrics' => [ 'icon' => 'dashboard', 'widget' => 'PhpDebugBar.Widgets.VariableListWidget', 'map' => 'api_metrics.metrics', 'default' => '{}', ], ]; } } // Register custom collector in config/debugbar.php 'custom_collectors' => [ ApiMetricsCollector::class => env('DEBUGBAR_COLLECTORS_API_METRICS', true), ], ``` ## Configuring Data Collectors Enable or disable built-in collectors and configure their options via the debugbar config file. ```php // config/debugbar.php return [ 'enabled' => env('DEBUGBAR_ENABLED'), // Enable/disable collectors 'collectors' => [ 'phpinfo' => true, // PHP version info 'messages' => true, // Debug messages 'time' => true, // Timeline and measures 'memory' => true, // Memory usage 'exceptions' => true, // Exceptions display 'log' => true, // Monolog messages 'db' => true, // Database queries 'views' => true, // Blade templates 'route' => true, // Current route info 'auth' => false, // Authentication status 'gate' => true, // Gate/policy checks 'session' => false, // Session data 'mail' => true, // Sent emails 'cache' => true, // Cache operations 'models' => true, // Eloquent models loaded 'livewire' => true, // Livewire components 'jobs' => true, // Dispatched jobs 'http_client' => true, // HTTP client requests ], // Collector-specific options 'options' => [ 'db' => [ 'with_params' => true, // Show query parameters 'backtrace' => true, // Show query origin 'timeline' => false, // Add queries to timeline 'duration_background' => true, // Visual duration indicator 'explain' => ['enabled' => true], // EXPLAIN queries 'soft_limit' => 100, // Limit before reducing detail 'hard_limit' => 500, // Maximum queries tracked ], 'views' => [ 'timeline' => true, // Add views to timeline 'data' => false, // Show view data (heavy) 'group' => 50, // Group duplicate views 'exclude_paths' => ['vendor/filament'], ], 'mail' => [ 'timeline' => true, 'show_body' => true, // Enable mail preview ], ], ]; ``` ## Database Query Collector Options Configure the database query collector to control how SQL queries are captured and displayed. ```php // config/debugbar.php - Database options 'options' => [ 'db' => [ // Render SQL with substituted parameters 'with_params' => true, // Paths to exclude from query collection 'exclude_paths' => [ 'vendor/laravel/framework/src/Illuminate/Session', ], // Show backtrace to find query origin 'backtrace' => true, 'backtrace_exclude_paths' => [], // Add queries to the timeline 'timeline' => false, // Visual duration background on queries 'duration_background' => true, // Enable on-demand EXPLAIN for SELECT queries 'explain' => [ 'enabled' => true, ], // Highlight slow queries (milliseconds, false to disable) 'slow_threshold' => 100, // Show query memory usage 'memory_usage' => false, // Query limits to prevent performance issues 'soft_limit' => 100, // Reduces detail after this count 'hard_limit' => 500, // Stops tracking after this count ], ], ``` ## Storage Configuration Configure how Debugbar stores request data for history browsing and AJAX request inspection. ```php // config/debugbar.php - Storage configuration 'storage' => [ 'enabled' => env('DEBUGBAR_STORAGE_ENABLED', true), // Allow browsing previous requests (security risk in production!) 'open' => env('DEBUGBAR_OPEN_STORAGE', false), // Storage driver: file, sqlite, redis, pdo, custom 'driver' => env('DEBUGBAR_STORAGE_DRIVER', 'file'), // Path for file/sqlite storage 'path' => storage_path('debugbar'), // Database connection for redis/pdo drivers 'connection' => null, // Custom storage provider class 'provider' => '', ], // For PDO storage, run migrations first: // php artisan migrate // Example .env configuration // DEBUGBAR_STORAGE_ENABLED=true // DEBUGBAR_STORAGE_DRIVER=file // DEBUGBAR_OPEN_STORAGE=true # Only for local development! ``` ## Laravel Octane Integration Configure Debugbar to work properly with Laravel Octane by adding it to the flush list. ```php // config/octane.php return [ // ... other octane config ... // Add LaravelDebugbar to the flush list 'flush' => [ \Fruitcake\LaravelDebugbar\LaravelDebugbar::class, ], ]; ``` ## Editor Integration Configure Debugbar to open files in your preferred code editor when clicking on file paths. ```php // config/debugbar.php // Supported editors: phpstorm, vscode, vscode-insiders, vscode-remote, // sublime, atom, nova, textmate, emacs, macvim, idea, netbeans, // xdebug, espresso, cursor, windsurf, zed 'editor' => env('DEBUGBAR_EDITOR', 'phpstorm'), // For remote development (Docker, Vagrant, etc.) 'remote_sites_path' => env('DEBUGBAR_REMOTE_SITES_PATH', '/var/www/html'), 'local_sites_path' => env('DEBUGBAR_LOCAL_SITES_PATH', '/Users/dev/projects'), // .env example for VS Code with Docker // DEBUGBAR_EDITOR=vscode // DEBUGBAR_REMOTE_SITES_PATH=/var/www/html // DEBUGBAR_LOCAL_SITES_PATH=/home/user/projects/myapp ``` ## AJAX Request Capture Configure how Debugbar handles AJAX and XHR requests with automatic tracking and Server-Timing headers. ```php // config/debugbar.php // Capture and display AJAX requests in debugbar dropdown 'capture_ajax' => true, // Send Server-Timing headers for Chrome DevTools 'add_ajax_timing' => false, // Auto-switch debugbar to show new AJAX requests 'ajax_handler_auto_show' => true, // Enable dedicated tab for AJAX requests 'ajax_handler_enable_tab' => true, // Defer loading dataset after request completes (experimental) 'defer_datasets' => false, ``` ## Excluding Routes from Debugbar Exclude specific routes from Debugbar injection using URI patterns. ```php // config/debugbar.php 'except' => [ 'telescope*', // Exclude Laravel Telescope routes 'horizon*', // Exclude Laravel Horizon routes 'api/*', // Exclude all API routes 'health-check', // Exclude specific route '_boost/browser-logs', ], ``` ## Twig Template Integration Use Debugbar with Twig templates via the provided extensions for debug output and timing. ```php // config/extensions.php (TwigBridge) return [ 'Fruitcake\LaravelDebugbar\Twig\Extension\Debug', 'Fruitcake\LaravelDebugbar\Twig\Extension\Dump', 'Fruitcake\LaravelDebugbar\Twig\Extension\Stopwatch', ]; ``` ```twig {# Debug variables to Debugbar Messages collector #} {{ debug() }} {# Dump all context variables #} {{ debug(user, categories) }} {# Dump specific variables #} {# Dump variables inline (replaces Twig dump) #} {{ dump(user) }} {# Measure execution time of template blocks #} {% stopwatch "sidebar-render" %} {% include 'partials/sidebar.twig' %} {% endstopwatch %} {% stopwatch "product-loop" %} {% for product in products %} {% include 'partials/product-card.twig' %} {% endfor %} {% endstopwatch %} ``` ## Manual JavaScript Renderer Manually inject the Debugbar when auto-injection is disabled, useful for custom layouts or SPA applications. ```php // Disable auto-injection in config // config/debugbar.php: 'inject' => false // In your controller or view composer use Fruitcake\LaravelDebugbar\Facades\Debugbar; $renderer = Debugbar::getJavascriptRenderer(); // Get the head assets (CSS and JS) $head = $renderer->renderHead(); // Get the toolbar HTML $widget = $renderer->render(); // In your Blade template <!DOCTYPE html> <html> <head> {!! $debugbarHead !!} </head> <body> <!-- Your content --> {!! $debugbarWidget !!} </body> </html> ``` ## Collecting Queued Jobs Data Enable job collection to debug dispatched jobs and view them in the history browser. ```php // .env DEBUGBAR_COLLECT_JOBS=true // Or in config/debugbar.php 'collect_jobs' => env('DEBUGBAR_COLLECT_JOBS', true), // Enable console/CLI debugging debugbar()->enable(); // In your Artisan command or job use Fruitcake\LaravelDebugbar\Facades\Debugbar; class ProcessOrderJob implements ShouldQueue { public function handle(): void { Debugbar::info('Processing order: ' . $this->order->id); Debugbar::startMeasure('payment', 'Payment processing'); $this->processPayment(); Debugbar::stopMeasure('payment'); // Job data viewable via Browse button in Debugbar } } ``` ## Clockwork Chrome Extension Support Enable Clockwork headers to use the Clockwork Chrome Extension without installing the Clockwork package. ```php // config/debugbar.php 'clockwork' => env('DEBUGBAR_CLOCKWORK', true), // .env DEBUGBAR_CLOCKWORK=true // Debugbar will send these headers: // X-Clockwork-Id: <request-id> // X-Clockwork-Version: 9 // X-Clockwork-Path: /_debugbar/clockwork/ ``` ## Theme Configuration Configure the Debugbar color theme to match your preferences or system settings. ```php // config/debugbar.php // Options: 'auto', 'light', 'dark' 'theme' => env('DEBUGBAR_THEME', 'auto'), // .env examples DEBUGBAR_THEME=dark // Always dark theme DEBUGBAR_THEME=light // Always light theme DEBUGBAR_THEME=auto // Follow system preference ``` Laravel Debugbar is primarily used for development debugging and performance profiling. Common use cases include: diagnosing slow database queries by viewing execution times and EXPLAIN output, debugging authentication and authorization issues via the Auth and Gate collectors, tracking mail delivery during development with the Mail collector's preview feature, and monitoring cache hit/miss ratios to optimize caching strategies. The history browser is particularly useful for debugging redirects, form submissions, and API endpoints that don't return HTML. Integration patterns typically involve installing Debugbar as a dev-only dependency and relying on the `APP_DEBUG` environment variable for automatic enabling. For team development, configure the editor integration to match each developer's IDE preference via environment variables. When using Docker or remote development environments, set up path mapping between container and host paths. For applications with high query counts, configure the soft/hard limits to prevent the Debugbar from impacting performance. Never enable Debugbar in production environments as it exposes sensitive application internals including session data, query parameters, and configuration values.