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

Trap Laravel Package

buggregator/trap

Buggregator Trap enhances PHP debugging with instant Symfony VarDumper integrations, handy helper functions, and a lightweight local Buggregator server (no Docker). Connect to any Buggregator server and pair with the PhpStorm plugin for a smooth workflow.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev buggregator/trap -W
    

    This adds Trap as a dev dependency and autoloads its functionality.

  2. First Use: Start the local server in a terminal:

    vendor/bin/trap
    

    The server will listen on default ports (9912, 9913, 1025, 8000) and display debug output in the console.

  3. First Debug Call: In your Laravel code, replace dump() or dd() with:

    trap($yourVariable);
    

    This sends the dump to the local Trap server (default sender: console).

Key First Use Cases

  • Replace dd(): Use td($var) to dump and die (equivalent to trap($var)->die()).
  • Stack Traces: Call trap()->stackTrace() to inspect the current call stack.
  • HTTP Requests: Trap automatically captures HTTP requests sent to 127.0.0.1 (no config needed).

Implementation Patterns

Core Workflows

1. Debugging in Laravel Controllers

public function show(Request $request, $id)
{
    $user = User::findOrFail($id);
    tr($user); // Shortcut for `trap($user)->return()`
    $response = $this->processData($user);
    return tr($response); // Dump response without breaking flow
}
  • Tip: Use tr() for quick debugging without breaking execution.

2. Conditional Dumping

trap($order)->if($order->isHighPriority())
             ->depth(2)
             ->times(1);
  • Use Case: Debug only specific conditions (e.g., failed payments) without cluttering logs.

3. Multi-Sender Configuration

Start the server with multiple senders (e.g., console + file):

vendor/bin/trap -sconsole -sfile
  • Laravel Integration: Store file dumps in storage/logs/trap/ for later review.

4. HTTP Request/Response Inspection

Trap automatically captures HTTP traffic to 127.0.0.1. For custom hosts:

trap()->http()->host('api.example.test');

5. Monolog/Sentry Integration

Configure Monolog to use Trap as a handler:

$monolog = new Monolog\Logger('name');
$monolog->pushHandler(new \Buggregator\Trap\Handler\TrapHandler());
  • Sentry: Use the sentry sender to forward errors to both Sentry and Trap.

Laravel-Specific Patterns

Service Container Binding

Bind Trap’s dumper to Laravel’s container for global access:

$this->app->singleton('trap', function () {
    return new \Buggregator\Trap\Dumper\Dumper();
});
  • Usage: Inject via constructor or resolve with $app['trap'].

Middleware for Debugging

Create middleware to trap requests/responses:

public function handle($request, Closure $next)
{
    $response = $next($request);
    tr($request->all(), response: $response->getContent());
    return $response;
}
  • Register: Add to app/Http/Kernel.php under $routeMiddleware.

Artisan Commands

Extend Trap’s functionality in custom Artisan commands:

public function handle()
{
    $this->info('Starting debug session...');
    trap()->stackTrace()->depth(5);
}

Testing

Use Trap to debug tests without cluttering output:

public function testUserCreation()
{
    $user = User::create([...]);
    tr($user); // Debug in terminal
    $this->assertDatabaseHas('users', $user->toArray());
}
  • Tip: Combine with --ui flag for a web interface during tests.

Gotchas and Tips

Pitfalls

  1. Port Conflicts:

    • Trap defaults to ports 9912, 9913, 1025, and 8000. If these are occupied:
      vendor/bin/trap -p9999 --ui=8081
      
    • Fix: Use environment variables (TRAP_TCP_PORTS, TRAP_UI_PORT) or specify custom ports.
  2. HTTP Traffic Capture:

    • Trap only captures traffic to 127.0.0.1 by default. For other hosts:
      trap()->http()->host('test.example.com');
      
    • Gotcha: Forgetting this may miss HTTP dumps in local testing.
  3. Performance Overhead:

    • Trap adds minimal overhead (~1-2ms per dump). Avoid excessive trap() calls in production.
    • Tip: Use ->times(N) to limit dumps in loops.
  4. Phar vs. Composer:

    • The Phar version (trap.phar) may not autoload Laravel services. Prefer Composer installation for Laravel projects.
  5. Symfony VarDumper Conflicts:

    • If using symfony/var-dumper, Trap extends its functionality. Ensure no duplicate handlers are registered.

Debugging Tips

  1. Stack Trace Depth:

    • Limit depth to avoid overwhelming output:
      trap($this)->depth(3);
      
  2. Conditional Dumping:

    • Use ->if() to debug specific branches:
      trap($user)->if($user->isAdmin());
      
  3. Return Values:

    • Use ->return() to dump and return the variable:
      $response = tr($this->getData());
      
  4. UI Mode:

    • Launch the web interface (experimental):
      vendor/bin/trap --ui
      
    • Access at http://localhost:8000 (or custom port).
  5. File Sender:

    • Dumps are saved to runtime/trap/ by default. Customize with:
      vendor/bin/trap -sfile -d/path/to/custom/dir
      

Extension Points

  1. Custom Senders:

    • Extend \Buggregator\Trap\Sender\SenderInterface to create custom handlers (e.g., Slack, Datadog).
  2. Protocol Handlers:

    • Add support for new protocols (e.g., gRPC) by implementing \Buggregator\Trap\Protocol\ProtocolInterface.
  3. Laravel Service Provider:

    • Create a provider to auto-configure Trap for all requests:
      public function boot()
      {
          if ($this->app->environment('local')) {
              trap()->http()->host($this->app->url());
          }
      }
      
  4. Monolog/Sentry Handlers:

    • Override default handlers to include Laravel-specific context (e.g., request ID, user agent).
  5. Phar Customization:

    • Rebuild the Phar with your dependencies using the build-phar script in the package’s scripts/ directory.

Config Quirks

  • Environment Variables:
    • TRAP_TCP_HOST: Override the default 127.0.0.1.
    • TRAP_LOG_LEVEL: Set log level (e.g., debug, info). Default: debug.
  • Laravel Cache:
    • Trap caches dumps in memory. Clear with trap()->clear() if needed.
  • Windows Paths:
    • Use forward slashes (/) or escape backslashes (\\) in file paths for cross-platform compatibility.

Pro Tips

  1. Debugging Exceptions:

    try {
        // Risky code
    } catch (\Exception $e) {
        td($e, trace: true); // Dump exception + stack trace
    }
    
  2. Database Queries:

    $query = User::query()->where(...);
    tr($query->toSql(), $query->getBindings());
    
  3. Queue Jobs:

    $job = new ProcessOrder($order);
    tr($job)->afterDispatch(); // Debug after job is dispatched
    
  4. Blade Templates:

    @php
        tr($user, compact('loop'));
    @endphp
    
  5. API Responses:

    return tr(response()->json($data))->header('X-Debug', 'true');
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope