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

symfony/var-dumper

Symfony VarDumper provides a powerful dump() replacement for var_dump(), letting you inspect complex PHP variables with rich, readable output. Includes advanced casters, configurable formatters, and tooling for debugging in CLI and web contexts.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/var-dumper
    

    Laravel already includes this package via Symfony’s dependencies, so no additional installation is required in most cases.

  2. First Use Case: Replace var_dump() or dd() with Symfony’s dump():

    use Symfony\Component\VarDumper\VarDumper;
    
    // Basic usage
    $user = User::find(1);
    VarDumper::dump($user);
    
    // Shortcut (Laravel already provides this via helpers)
    dump($user); // Alias for VarDumper::dump()
    dd($user);   // Alias for dump() + die()
    
  3. Where to Look First:

    • Documentation: Symfony VarDumper Docs
    • Laravel Integration: Built into Laravel’s dump() and dd() helpers (no extra config needed).
    • CLI vs. Web Output:
      • CLI: Colorized, interactive output (supports pagination with q to quit).
      • Web: HTML-formatted output (useful for debugging API responses or Blade templates).

Implementation Patterns

Core Workflows

1. Debugging Eloquent Models and Relationships

// Debug a user with nested relationships
$user = User::with('posts.comments')->find(1);
dump($user); // Shows relationships in a collapsible tree

// Debug a specific relationship
dump($user->posts->where('published', true)->load('author'));

2. API Response Inspection

// Debug API responses (works with Laravel HTTP clients)
$response = Http::get('https://api.example.com/data');
dump($response->json()); // Pretty-printed JSON with syntax highlighting

// Debug Symfony HTTP responses (if using Symfony components)
$response = $client->request('GET', '/endpoint');
dump($response->getContent());

3. Queue Job Debugging

// Debug queue payloads (e.g., in a job class)
public function handle()
{
    dump('Job payload:', $this->data); // Inspect job data
    dump('Exception:', $this->exception); // If job fails
}

4. CLI and Artisan Command Debugging

// Debug Artisan command input/output
public function handle()
{
    dump('Input:', $this->argument('input'));
    dump('Options:', $this->option('verbose'));
}

5. Event Listener Debugging

public function handle(OrderPlaced $event)
{
    dump('Event payload:', $event->order); // Inspect event data
}

Integration Tips

1. Custom Casters for Eloquent Models

Extend VarDumper to handle custom objects (e.g., Eloquent models with complex attributes):

use Symfony\Component\VarDumper\Caster\Caster;

class EloquentModelCaster implements Caster
{
    public function __invoke($model)
    {
        return [
            'class' => get_class($model),
            'attributes' => $model->attributesToArray(),
            'relations' => $model->relations,
        ];
    }

    public function getType()
    {
        return 'eloquent_model';
    }
}

// Register the caster (e.g., in a service provider)
VarDumper::addCaster(new EloquentModelCaster());

2. Debugging in Blade Templates

Use dump() in Blade to inspect variables during template rendering:

@dump($user) {{-- Renders HTML output in browser --}}
@dd($user)  {{-- Renders and stops execution --}}

3. Conditional Debugging

Use Laravel’s debug mode to toggle VarDumper output:

if (app()->environment('local')) {
    dump('Debug data:', $variable);
}

4. Debugging Exceptions

Catch exceptions and dump them for debugging:

try {
    // Risky operation
} catch (\Exception $e) {
    dump('Exception:', $e);
    throw $e;
}

5. Debugging Large Collections

Avoid dumping large datasets by limiting results:

$largeCollection = User::all();
dump($largeCollection->take(10)); // Only dump first 10 items

6. Integration with Laravel Debugbar

If using barryvdh/laravel-debugbar, VarDumper’s output can be redirected to the debug bar:

use Barryvdh\Debugbar\Debugbar;

Debugbar::info(VarDumper::dump($variable));

Gotchas and Tips

Pitfalls

  1. Memory Usage:

    • Dumping large objects (e.g., entire database tables) can cause memory exhaustion.
    • Fix: Use ->take(N) or sample data before dumping.
  2. Sensitive Data Exposure:

    • Accidental dump() calls in production can leak sensitive data (passwords, tokens).
    • Fix: Wrap debug code in if (app()->environment('local')) or use feature flags.
  3. Performance Overhead:

    • VarDumper adds CPU/memory overhead during debugging. Avoid in production or high-traffic routes.
    • Fix: Disable in production (APP_DEBUG=false) or use structured logging.
  4. CLI vs. Web Output Mismatch:

    • CLI output is colorized and interactive, while web output is HTML-only.
    • Fix: Use dump() in CLI and @dump() in Blade for consistent debugging.
  5. Custom Object Dumping:

    • Complex objects (e.g., closures, resources, or proprietary classes) may not dump cleanly.
    • Fix: Implement custom casters (see Implementation Patterns).
  6. Deprecated Methods:

    • Older versions of VarDumper may use deprecated methods (e.g., __sleep()).
    • Fix: Update to the latest version or patch with __serialize()/__unserialize().

Debugging Tips

  1. Inspecting Request/Response Cycles: Use middleware to dump requests/responses:

    public function handle($request, Closure $next)
    {
        dump('Request:', $request->all());
        $response = $next($request);
        dump('Response:', $response->getContent());
        return $response;
    }
    
  2. Debugging Laravel Services: Dump service container bindings:

    dump(app()->bindings()); // List all service bindings
    dump(app('db'));         // Inspect database connection
    
  3. Debugging Blade Directives: Create a custom Blade directive for debugging:

    Blade::directive('debug', function ($expression) {
        return "<?php dump({$expression}); ?>";
    });
    

    Usage:

    @debug($user)
    
  4. Debugging Queue Failures: Use a job middleware to dump failed jobs:

    public function handle($job, $next)
    {
        try {
            return $next($job);
        } catch (\Exception $e) {
            dump('Failed job:', $job->payload());
            throw $e;
        }
    }
    
  5. Debugging Symfony Events: Dump event dispatchers or listeners:

    dump($dispatcher->getListeners('event.name')); // List listeners
    

Extension Points

  1. Custom Casters:

    • Override how specific classes are dumped (e.g., for Eloquent models, custom collections, or third-party libraries).
    • Example: Symfony’s Caster System.
  2. Output Formatters:

    • Extend ClonerInterface or DumperInterface to customize output (e.g., JSON, XML, or custom formats).
    • Example: HtmlDumper for web output.
  3. Integration with Laravel:

    • Override Laravel’s dump()/dd() helpers in app/Helpers.php or a service provider:
      if (!function_exists('custom_dump')) {
          function custom_dump(...$args) {
              // Custom logic (e.g., log to a file, filter sensitive data)
              VarDumper::dump(...$args);
          }
      }
      
  4. CLI Enhancements:

    • Use Symfony’s Cloner to serialize data for CLI tools:
      use Symfony\Component\VarDumper\Cloner\Cloner;
      
      $cloner = new Cloner();
      $serialized = $cloner
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport