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

Var Dumper Laravel Package

yiisoft/var-dumper

Yii VarDumper enhances var_dump()/var_export() with safe handling of recursive references, syntax highlighting, and closure export. Includes handy d(), dump(), and dd() helpers for quick debugging. Configurable depth and highlighting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Update Composer to target PHP 8.0–8.5 (required for this release):

    composer require yiisoft/var-dumper:^1.7.1
    

    No additional configuration is required—it remains a standalone utility.

  2. First Use Case Dump a variable in a Laravel controller or Blade template (PHP 8.0–8.5 only):

    use Yiisoft\VarDumper\VarDumper;
    
    // In a controller
    public function show(Request $request) {
        $data = $request->all();
        VarDumper::dump($data);
        // Outputs improved HTML syntax-highlighted dumps in browsers and colored CLI output.
    }
    
  3. Where to Look First

    • CLI vs. Web Output: Auto-detection persists, but HTML syntax highlighting in browsers is now enhanced (see #112).
    • Documentation: YiiSoft VarDumper 1.7 Docs (check for PHP 8.0+ specifics).
    • Laravel Integration: Works with Laravel’s dd() helpers, but ensure your app uses PHP 8.0–8.5.

Implementation Patterns

Usage Patterns

  1. Replacing dd() or dump() (PHP 8.0+) Replace Laravel’s dd() (halts execution) or dump() (console-only) with VarDumper for consistent, syntax-highlighted output:

    // Instead of:
    dd($user); // Halts execution (PHP 8.0+ compatible)
    dump($user); // Console-only
    
    // Use:
    VarDumper::dump($user); // Works in CLI/browser, with improved HTML syntax highlighting.
    
  2. Leveraging Enhanced HTML Output

    • Browser: Arrays/objects now render with syntax-highlighted HTML (e.g., JSON-like formatting for collections). Example output for $request->all():
      <pre class="var-dump">
        <span class="var-dump-key">"user"</span>: <span class="var-dump-value">"john"</span>,
        <span class="var-dump-key">"roles"</span>: [
          <span class="var-dump-value">"admin"</span>,
          <span class="var-dump-value">"editor"</span>
        ]
      </pre>
      
    • CLI: Colors and formatting remain unchanged but are now optimized for PHP 8.0–8.5.
  3. Customizing Output for PHP 8.0+

    • Type-Specific Handlers: Use PHP 8.0+ features (e.g., TypedArray, WeakMap) with custom handlers:
      VarDumper::setHandler(new class implements VarDumperHandlerInterface {
          public function handle($var) {
              if ($var instanceof TypedArray) {
                  return "TypedArray(" . count($var) . ")";
              }
              return VarDumper::dumpAsString($var);
          }
      });
      
  4. Logging Debug Data Log formatted dumps to Laravel’s log system (PHP 8.0+):

    use Illuminate\Support\Facades\Log;
    
    Log::debug(VarDumper::dumpAsString($this->request->headers));
    

Workflows

  • Debugging API Requests (PHP 8.0+)

    public function api(Request $request) {
        VarDumper::dump($request->json()->all());
        // Outputs syntax-highlighted JSON in browser/CLI.
    }
    
  • Database Query Debugging

    $users = User::where('active', true)->get();
    VarDumper::dump($users->toArray());
    // Collections render with improved HTML structure.
    
  • Event Listeners (PHP 8.0+)

    public function handle(UserLoggedIn $event) {
        VarDumper::dump($event->user->with('roles')->toArray());
        // Nested relationships display with syntax highlighting.
    }
    

Integration Tips

  • Laravel Debugbar: Pair with barryvdh/laravel-debugbar for enhanced panels (ensure PHP 8.0+ compatibility).
  • Telescope: Format dumps for Telescope by extending VarDumper handlers.
  • Testing: Dump test data in PHPUnit (PHP 8.0+):
    public function testUserCreation() {
        $user = User::create([...]);
        VarDumper::dump($user->fresh());
        // ...
    }
    

Gotchas and Tips

Pitfalls

  1. PHP Version Constraint (BREAKING)

    • Issue: This release requires PHP 8.0–8.5. Older versions (e.g., 7.4) will fail.
    • Fix: Update your Laravel app’s PHP version or pin to yiisoft/var-dumper:^1.6 if stuck on PHP <8.0.
  2. Performance Overhead

    • Issue: Syntax-highlighted HTML output may increase rendering time in browsers.
    • Fix: Use environment checks:
      if (app()->environment('local')) {
          VarDumper::dump($variable);
      }
      
  3. Circular References

    • Issue: Deeply nested objects may still cause infinite loops.
    • Fix: Use setMaxItems() (PHP 8.0+):
      VarDumper::setMaxItems(50); // Limit nested items.
      
  4. HTML Output in APIs

    • Issue: Dumping in API routes returns HTML instead of JSON.
    • Fix: Restrict usage to non-API routes or use dumpAsString():
      return response()->json(['debug' => VarDumper::dumpAsString($data)]);
      

Debugging Tips

  • Disable Output Temporarily Override the handler to suppress output (PHP 8.0+):

    VarDumper::setHandler(new class {
        public function handle($var) { return null; }
    });
    
  • Log Dumps to File

    file_put_contents(
        storage_path('logs/debug_dump.log'),
        VarDumper::dumpAsString($variable)
    );
    
  • Custom Exceptions Catch and log dumps for errors (PHP 8.0+):

    try {
        $result = riskyOperation();
    } catch (\Exception $e) {
        VarDumper::dump($context);
        throw $e;
    }
    

Extension Points

  1. Custom Handlers for PHP 8.0+ Types Register handlers for PHP 8.0+ features (e.g., Attribute, WeakReference):

    VarDumper::setHandler(new class implements VarDumperHandlerInterface {
        public function handle($var) {
            if ($var instanceof Attribute) {
                return "Attribute: " . $var->getName();
            }
            return VarDumper::dumpAsString($var);
        }
    });
    
  2. Override Default Formatter Replace the formatter for global changes (PHP 8.0+):

    VarDumper::setFormatter(new \Yiisoft\VarDumper\Formatter\HtmlFormatter());
    
  3. Laravel Service Provider (PHP 8.0+) Bind VarDumper to the container:

    // In AppServiceProvider
    $this->app->singleton(VarDumper::class, function () {
        return new VarDumper();
    });
    
  4. Blade Directives (PHP 8.0+) Create a custom Blade directive:

    // In AppServiceProvider
    Blade::directive('dump', function ($expression) {
        return "<?php echo Yiisoft\VarDumper\VarDumper::dump({$expression}); ?>";
    });
    

    Usage:

    @dump($variable)
    

Config Quirks

  • No Configuration File: Runtime-only settings (e.g., setMaxItems()).
  • Thread Safety: Safe in queues/jobs, but avoid large dumps in production.
  • Memory Limits: Large dumps may hit PHP’s memory_limit. Use:
    VarDumper::setMaxString(100); // Truncate strings >100 chars.
    VarDumper::setMaxItems(50);   // Limit nested items.
    
  • HTML Output: Syntax highlighting is now opt-in for custom formatters. Default EchoHandler includes it.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui