Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Laravel Telescope
https://github.com/laravel/telescope
Admin
Laravel Telescope is an elegant debug assistant for the Laravel framework, providing insight into
...
Tokens:
5,506
Snippets:
32
Trust Score:
9.4
Update:
5 months ago
Context
Skills
Chat
Benchmark
71.9
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Laravel Telescope Laravel Telescope is an elegant debug assistant for the Laravel framework that provides deep insight into application operations. It captures and displays requests, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps, and more in a beautiful web-based dashboard. Telescope serves as a comprehensive monitoring and debugging companion for Laravel development environments. The package operates through a system of watchers that listen to Laravel framework events and record entries to a database repository. Each watcher monitors specific aspects of the application (queries, requests, exceptions, etc.), transforms the data into standardized entry objects, and stores them for viewing through Telescope's web interface. The system includes advanced features like tag monitoring, entry filtering, recording control, and automatic data pruning to maintain database health. ## Installation and Setup Install and configure Telescope in a Laravel application. ```bash # Install via Composer composer require laravel/telescope # Run installation command php artisan telescope:install # Run migrations php artisan migrate ``` ```php // config/telescope.php - Basic configuration return [ 'enabled' => env('TELESCOPE_ENABLED', true), 'path' => env('TELESCOPE_PATH', 'telescope'), 'driver' => env('TELESCOPE_DRIVER', 'database'), 'storage' => [ 'database' => [ 'connection' => env('DB_CONNECTION', 'mysql'), 'chunk' => 1000, ], ], ]; // Access dashboard at: http://your-app.test/telescope ``` ## Recording Control Start, stop, and conditionally control Telescope recording. ```php use Laravel\Telescope\Telescope; // Start recording Telescope::startRecording(); // Stop recording Telescope::stopRecording(); // Check if recording if (Telescope::isRecording()) { // Telescope is actively recording } // Execute code without recording Telescope::withoutRecording(function () { // This database query won't be recorded User::all(); }); // Pause recording via cache (persists across requests) cache()->put('telescope:pause-recording', true); // Resume recording cache()->forget('telescope:pause-recording'); ``` ## Entry Filtering Filter which entries are recorded based on custom logic. ```php use Laravel\Telescope\Telescope; use Laravel\Telescope\IncomingEntry; // app/Providers/TelescopeServiceProvider.php public function register() { Telescope::filter(function (IncomingEntry $entry) { if ($this->app->environment('local')) { return true; // Record everything in local } // In production, only record exceptions, failed jobs, and slow queries return $entry->isReportableException() || $entry->isFailedJob() || $entry->isSlowQuery() || $entry->isFailedRequest() || $entry->hasMonitoredTag(); }); // Filter entire batches Telescope::filterBatch(function ($entries) { // Reject batch if it contains only cache operations return $entries->contains(fn ($e) => $e->type !== 'cache'); }); } ``` ## Custom Tags Add custom tags to entries for filtering and monitoring. ```php use Laravel\Telescope\Telescope; // app/Providers/TelescopeServiceProvider.php public function register() { Telescope::tag(function (IncomingEntry $entry) { $tags = []; // Tag by user if ($entry->user) { $tags[] = 'user:' . $entry->user->id; } // Tag slow queries if ($entry->isSlowQuery()) { $tags[] = 'slow'; } // Tag by request path if ($entry->isRequest()) { $tags[] = 'path:' . $entry->content['uri']; } // Tag API requests if ($entry->isRequest() && str_starts_with($entry->content['uri'], '/api/')) { $tags[] = 'api'; } return $tags; }); } ``` ## Query Watcher Configuration Monitor and track database queries with performance metrics. ```php // config/telescope.php 'watchers' => [ Watchers\QueryWatcher::class => [ 'enabled' => env('TELESCOPE_QUERY_WATCHER', true), 'ignore_packages' => true, 'ignore_paths' => [], 'slow' => 100, // Queries taking more than 100ms are tagged as slow ], ]; // The QueryWatcher automatically records: // - SQL query with bindings replaced // - Connection name and driver // - Execution time // - File and line number where query originated // - Slow query flag based on threshold ``` ```php // Example recorded query entry structure: [ 'connection' => 'mysql', 'driver' => 'mysql', 'bindings' => [], 'sql' => "select * from users where email = 'user@example.com'", 'time' => '45.23', 'slow' => false, 'file' => '/app/Http/Controllers/UserController.php', 'line' => 42, 'hash' => 'a3f5b2c1d4e6...', ] ``` ## Request Watcher Configuration Track HTTP requests with headers, payload, and response data. ```php // config/telescope.php 'watchers' => [ Watchers\RequestWatcher::class => [ 'enabled' => env('TELESCOPE_REQUEST_WATCHER', true), 'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64), // KB 'ignore_http_methods' => ['OPTIONS'], 'ignore_status_codes' => [404, 403], ], ]; // Hide sensitive data Telescope::hideRequestParameters(['password', 'password_confirmation', 'api_key']); Telescope::hideRequestHeaders(['authorization', 'php-auth-pw', 'x-api-token']); Telescope::hideResponseParameters(['token', 'secret']); ``` ```php // Example recorded request entry: [ 'ip_address' => '192.168.1.1', 'uri' => '/api/users', 'method' => 'POST', 'controller_action' => 'App\Http\Controllers\UserController@store', 'middleware' => ['web', 'auth', 'verified'], 'headers' => ['content-type' => 'application/json'], 'payload' => ['name' => 'John Doe', 'password' => '********'], 'session' => [], 'response_headers' => ['content-type' => 'application/json'], 'response_status' => 201, 'response' => ['user' => ['id' => 1, 'name' => 'John Doe']], 'duration' => 342, // milliseconds 'memory' => 24.5, // MB ] ``` ## Exception Recording Capture and track exceptions with context and occurrence counts. ```php use Laravel\Telescope\Telescope; // Manually record an exception try { // Some risky operation processPayment($order); } catch (\Exception $e) { // Record with custom tags Telescope::catch($e, ['payment', 'critical']); // Continue handling throw $e; } // Exceptions are automatically tracked by ExceptionWatcher // Each exception includes: // - Exception class and message // - Stack trace with file and line numbers // - Occurrence count (grouped by exception family) // - Context and user information ``` ## Tag Monitoring Monitor specific tags to always record matching entries. ```php use Laravel\Telescope\Contracts\EntriesRepository; // Start monitoring specific tags $repository = app(EntriesRepository::class); // Monitor all requests from a specific user $repository->monitor(['user:123']); // Monitor API endpoints $repository->monitor(['api']); // Get currently monitored tags $monitoredTags = $repository->monitoring(); // Returns: ['user:123', 'api'] // Stop monitoring $repository->stopMonitoring(['user:123']); // Entries with monitored tags are always recorded even if filters would reject them ``` ## Custom Entry Recording Record custom entries programmatically. ```php use Laravel\Telescope\IncomingEntry; use Laravel\Telescope\Telescope; // Record a custom log entry Telescope::recordLog(IncomingEntry::make([ 'level' => 'info', 'message' => 'Payment processed successfully', 'context' => [ 'order_id' => 12345, 'amount' => 99.99, 'payment_method' => 'credit_card', ], ])); // Record a custom event Telescope::recordEvent(IncomingEntry::make([ 'name' => 'OrderShipped', 'payload' => [ 'order_id' => 12345, 'tracking_number' => 'ABC123XYZ', ], ])); // All custom entries automatically include: // - UUID // - Timestamp // - Hostname // - Authenticated user (if any) ``` ## Database Repository Operations Query and manage stored Telescope entries. ```php use Laravel\Telescope\Storage\EntryQueryOptions; use Laravel\Telescope\Contracts\EntriesRepository; $repository = app(EntriesRepository::class); // Find entry by UUID $entry = $repository->find('9a0f2e8b-3c1d-4a5e-8f7b-6c9d8e7f6a5b'); // Get entries with options $options = new EntryQueryOptions(); $options->limit = 50; $queries = $repository->get('query', $options); foreach ($queries as $query) { echo $query->content['sql'] . "\n"; echo "Time: " . $query->content['time'] . "ms\n"; } // Clear all entries $repository->clear(); // Check if monitoring tags if ($repository->isMonitoring(['user:123'])) { // This user is being monitored } ``` ## Artisan Commands Manage Telescope via command-line interface. ```bash # Prune old entries (keep last 24 hours) php artisan telescope:prune # Prune but keep exceptions php artisan telescope:prune --keep-exceptions # Prune entries older than 7 days php artisan telescope:prune --hours=168 # Clear all entries php artisan telescope:clear # Pause recording php artisan telescope:pause # Resume recording php artisan telescope:resume # Publish assets and config php artisan telescope:publish ``` ```php // Schedule automatic pruning in app/Console/Kernel.php protected function schedule(Schedule $schedule) { // Prune entries older than 48 hours daily $schedule->command('telescope:prune --hours=48') ->daily(); } ``` ## Path and Domain Configuration Configure where Telescope is accessible. ```php // config/telescope.php return [ // Custom subdomain 'domain' => env('TELESCOPE_DOMAIN', 'telescope.example.com'), // Custom path 'path' => env('TELESCOPE_PATH', 'admin/telescope'), // Only monitor specific paths 'only_paths' => [ 'api/*', ], // Ignore specific paths 'ignore_paths' => [ 'livewire*', 'nova-api*', 'pulse*', ], // Ignore specific commands 'ignore_commands' => [ 'inspire', 'package:discover', ], ]; // Access at: http://telescope.example.com // Or: http://your-app.test/admin/telescope ``` ## Authorization Control who can access the Telescope dashboard. ```php // app/Providers/TelescopeServiceProvider.php use Laravel\Telescope\Telescope; protected function gate() { Telescope::auth(function ($request) { // Allow in local environment if (app()->environment('local')) { return true; } // Check user authorization return in_array($request->user()?->email, [ 'admin@example.com', 'developer@example.com', ]); }); } ``` ## Watcher Configuration Enable/disable and configure individual watchers. ```php // config/telescope.php 'watchers' => [ // Simple on/off Watchers\BatchWatcher::class => env('TELESCOPE_BATCH_WATCHER', true), Watchers\JobWatcher::class => true, Watchers\MailWatcher::class => false, // Disabled // Advanced configuration Watchers\CacheWatcher::class => [ 'enabled' => true, 'hidden' => ['session:*'], // Hide session cache keys 'ignore' => ['telescope:*'], // Ignore telescope's own cache ], Watchers\ModelWatcher::class => [ 'enabled' => true, 'events' => ['eloquent.*'], // All model events 'hydrations' => true, // Track model hydrations ], Watchers\LogWatcher::class => [ 'enabled' => true, 'level' => 'error', // Only log errors and above ], Watchers\GateWatcher::class => [ 'enabled' => true, 'ignore_abilities' => ['viewNova'], 'ignore_packages' => true, 'ignore_paths' => ['nova*'], ], ]; ``` ## After Recording Hook Execute code after entries are recorded. ```php use Laravel\Telescope\Telescope; // app/Providers/TelescopeServiceProvider.php public function register() { Telescope::afterRecording(function ($telescope, $entry) { // Send alert for exceptions in production if (app()->environment('production') && $entry->isException()) { // Send Slack notification Notification::route('slack', env('SLACK_WEBHOOK')) ->notify(new ExceptionOccurred($entry)); } // Log slow queries if ($entry->isSlowQuery()) { Log::warning('Slow query detected', [ 'sql' => $entry->content['sql'], 'time' => $entry->content['time'], ]); } }); } ``` ## After Storing Hook Execute code after entries are stored in database. ```php use Laravel\Telescope\Telescope; // app/Providers/TelescopeServiceProvider.php public function register() { Telescope::afterStoring(function ($entries, $batchId) { // Entries is a collection of IncomingEntry objects $exceptionCount = $entries->filter->isException()->count(); if ($exceptionCount > 10) { // Alert if too many exceptions in single batch alert("High exception rate: {$exceptionCount} exceptions in batch {$batchId}"); } // Update metrics Metrics::increment('telescope.entries.stored', $entries->count()); }); } ``` ## API Endpoints Access Telescope data via HTTP API. ```bash # Get all queries (POST request for filtering) curl -X POST http://your-app.test/telescope-api/queries \ -H "Content-Type: application/json" \ -d '{"limit": 50}' # Get specific query entry curl http://your-app.test/telescope-api/queries/9a0f2e8b-3c1d-4a5e-8f7b-6c9d8e7f6a5b # Get all requests curl -X POST http://your-app.test/telescope-api/requests # Get exceptions curl -X POST http://your-app.test/telescope-api/exceptions # View mail preview curl http://your-app.test/telescope-api/mail/{entryId}/preview # Get monitored tags curl http://your-app.test/telescope-api/monitored-tags # Add monitored tag curl -X POST http://your-app.test/telescope-api/monitored-tags \ -H "Content-Type: application/json" \ -d '{"tag": "user:123"}' # Toggle recording curl -X POST http://your-app.test/telescope-api/toggle-recording # Clear all entries curl -X DELETE http://your-app.test/telescope-api/entries ``` ## Dark Theme Enable dark theme for the dashboard. ```php use Laravel\Telescope\Telescope; // app/Providers/TelescopeServiceProvider.php public function register() { Telescope::night(); } ``` ## Queue Configuration Configure how Telescope processes entry updates. ```php // config/telescope.php 'queue' => [ 'connection' => env('TELESCOPE_QUEUE_CONNECTION', 'redis'), 'queue' => env('TELESCOPE_QUEUE', 'telescope'), 'delay' => env('TELESCOPE_QUEUE_DELAY', 10), // seconds ], // Entry updates are dispatched to queue for async processing // This prevents blocking the main request/response cycle ``` ## Laravel Telescope serves as a comprehensive debugging and monitoring solution for Laravel applications, making it invaluable during development and useful for production monitoring with proper filtering. Its watcher system provides granular control over what gets recorded, while tag monitoring and filtering ensure you capture exactly what matters. The web dashboard offers an intuitive interface for exploring requests, queries, exceptions, and other application events. Integration patterns typically involve installing Telescope in development environments with full recording enabled, while production environments use strict filtering to only record exceptions, slow queries, failed jobs, and monitored tags. Custom tags and authorization gates ensure sensitive data remains protected. Regular pruning via scheduled commands keeps the database lean, and the comprehensive API allows building custom monitoring dashboards or integrating Telescope data with external monitoring services. The package's hooks (afterRecording, afterStoring) enable real-time alerting and metrics collection based on recorded entries.