Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Telescope Mongodb Laravel Package

webrek/laravel-telescope-mongodb

Drop-in MongoDB storage driver for Laravel Telescope. Run Telescope without MySQL/PostgreSQL: install via artisan, publishes assets, removes SQL migrations, creates required MongoDB indexes, and binds the repository. Includes command to migrate existing SQL Telescope data.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require webrek/laravel-telescope-mongodb
    php artisan telescope-mongodb:install
    
    • This handles:
      • Publishing Telescope assets (Blade views, JS, CSS).
      • Removing the default SQL migration (irrelevant for MongoDB).
      • Creating 7 critical indexes in MongoDB (required for Telescope’s query performance).
      • Binding the MongoDB driver to Telescope’s EntriesRepository.
  2. First Use Case:

    • Visit /telescope in your browser. The dashboard will now populate with:
      • HTTP requests (with payloads, headers, and metadata).
      • Exceptions (stack traces, context).
      • Queued jobs (status, payloads).
      • Database queries (MongoDB operations included).
      • Log entries (structured logs).
      • Notifications and mails (if using Laravel’s notification/mail systems).
  3. Prerequisites Check:

    • Ensure jenssegers/laravel-mongodb is installed (this package depends on it).
    • Verify your config/database.php has a MongoDB connection configured (e.g., mongodb).

Implementation Patterns

Core Workflows

  1. Replacing SQL with MongoDB:

    • Telescope’s default telescope_entries table is replaced by a MongoDB collection (telescope_entries by default).
    • No schema migrations: The package skips SQL migrations entirely, relying on MongoDB’s schema-less nature.
    • Indexing: The installer creates indexes for:
      • type (e.g., request, exception).
      • created_at (for time-based queries).
      • tags (for filtering).
      • Composite indexes for joins (e.g., type + id).
  2. Integrating with Existing Telescope:

    • Drop-in replacement: No changes to Telescope’s core logic. The package hooks into Laravel’s service container to override the EntriesRepository.
    • Middleware: Ensure TelescopeServiceProvider is registered in config/app.php (handled by the installer).
    • Environment: Add to .env:
      TELESCOPE_ENABLED=true
      TELESCOPE_DATABASE=mongodb
      
  3. Querying Data:

    • Use Telescope’s existing Blade components (e.g., @telescope) or API endpoints (/telescope/entries).
    • MongoDB-specific queries: Leverage MongoDB’s aggregation pipeline via Telescope’s API:
      $entries = Telescope::entries()
          ->where('type', 'exception')
          ->where('tags', 'auth')
          ->orderBy('created_at', 'desc')
          ->get();
      
    • Performance: Avoid large limit() calls without skip()—MongoDB’s cursor behavior differs from SQL.
  4. Customizing Collections:

    • Override the default collection name in config/telescope.php:
      'mongodb' => [
          'collection' => 'custom_telescope_entries',
      ],
      
    • Re-run the installer to update indexes if the collection name changes.
  5. Handling Large Datasets:

    • TTL Indexes: Add a TTL index to auto-expire old entries (e.g., 30 days):
      Schema::connection('mongodb')->collection('telescope_entries')->createIndex(
          ['created_at' => 1],
          ['expireAfterSeconds' => 2592000] // 30 days
      );
      
    • Archiving: Use MongoDB’s aggregate() to archive data to a separate collection:
      $archive = Telescope::entries()
          ->match(['created_at' => ['$lt' => now()->subDays(90)]])
          ->aggregate([['$out' => 'telescope_archive']]);
      

Gotchas and Tips

Pitfalls

  1. Missing Indexes:

    • Symptom: Slow queries or missing data in Telescope’s UI.
    • Fix: Re-run php artisan telescope-mongodb:install or manually create the 7 required indexes:
      Schema::connection('mongodb')->collection('telescope_entries')->createIndex('type');
      Schema::connection('mongodb')->collection('telescope_entries')->createIndex('created_at');
      // ... (repeat for all 7 indexes listed in the package's docs).
      
  2. Schema Changes:

    • Issue: MongoDB’s schema-less nature can cause inconsistencies if Telescope’s entry structure changes across Laravel versions.
    • Solution: Monitor Laravel Telescope updates and manually adjust MongoDB indexes if new fields are added to entries.
  3. Memory Usage:

    • Problem: Large collections (e.g., >1M entries) may cause high memory usage during queries.
    • Mitigation:
      • Use allowDiskUse(true) in aggregation queries.
      • Implement client-side pagination in Telescope’s Blade views.
  4. Timezone Handling:

    • Gotcha: MongoDB stores created_at as UTC by default, but Telescope may display it in the app’s timezone.
    • Fix: Ensure config/app.php has consistent timezone settings and Telescope’s created_at is formatted correctly in Blade:
      {{ $entry->created_at->tz('UTC')->format('Y-m-d H:i:s') }}
      
  5. Concurrent Writes:

    • Risk: High write volumes (e.g., during deployments) may cause duplicate entries or race conditions.
    • Workaround: Use MongoDB’s insertOne with ordered: false in the driver’s write operations (if customizing the package).

Debugging Tips

  1. Check MongoDB Logs:

    • Enable MongoDB’s profiling level to debug slow queries:
      db.setProfilingLevel(1, { slowms: 50 });
      db.system.profile.find().sort({ ts: -1 }).limit(10);
      
  2. Verify Index Usage:

    • Query MongoDB’s index usage:
      db.telescope_entries.aggregate([{ $indexStats: {} }]);
      
  3. Test Locally:

    • Use TELESCOPE_ENABLED=false in production until fully tested. MongoDB’s performance characteristics (e.g., indexing) may differ from SQL.

Extension Points

  1. Custom Entry Types:

    • Extend Telescope’s entry types by publishing the package’s config and adding new MongoDB indexes:
      // config/telescope-mongodb.php
      'custom_indexes' => [
          'custom_type_1' => ['field1', 'field2'],
      ];
      
    • Re-run the installer to apply custom indexes.
  2. Overriding the Driver:

    • Publish the driver’s config and bind a custom EntriesRepository:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->bind(
              \Laravel\Telescope\EntriesRepository::class,
              \Webrek\TelescopeMongoDB\Repositories\CustomEntriesRepository::class
          );
      }
      
  3. Adding Fields to Entries:

    • If Telescope’s default entry structure lacks fields (e.g., user_id), extend the TelescopeEntry model:
      namespace App\Models;
      use Webrek\TelescopeMongoDB\Models\TelescopeEntry as BaseEntry;
      
      class TelescopeEntry extends BaseEntry
      {
          protected $casts = [
              'user_id' => 'integer',
          ];
      }
      
    • Update the MongoDB schema by re-running migrations or manually adding the field to existing documents.
  4. API Extensions:

    • Add custom API routes for MongoDB-specific queries:
      Route::middleware(['web', 'telescope'])
           ->get('/telescope/custom-query', function () {
               return Telescope::entries()
                   ->match(['tags' => 'api'])
                   ->project(['method', 'path', 'duration'])
                   ->toArray();
           });
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony