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 Ray Laravel Package

spatie/laravel-ray

Send Laravel debug output to Ray, Spatie’s desktop debugger. Use a consistent “ray()” API to inspect variables, arrays, HTML, queries, and more, measure performance, and pause execution. Works alongside PHP, JS, and other integrations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-ray
    php artisan ray:install
    

    This publishes the config file and installs the Ray CLI tool.

  2. First Use Case: Replace dd() or dump() with Ray’s directives in your Laravel app:

    ray('User data', $user); // Logs user data to Ray
    ray(new User); // Auto-detects Eloquent models
    
  3. Launch Ray:

    • Open the Ray desktop app (free trial available).
    • Ensure your Laravel app is running (php artisan serve).
    • Ray will automatically capture logs from your app.

Key First Steps

  • Configure Environment: Set RAY_APP_ID in .env (generated during installation).
  • Test Output: Use ray('Test message') in a route or controller to verify integration.
  • Explore UI: Familiarize yourself with Ray’s UI (collapsible logs, variable inspection, and performance tabs).

Implementation Patterns

Core Workflows

1. Debugging Variables

Replace dd() with ray() for non-destructive inspection:

// Before
dd($request->all());

// After
ray('Request data', $request->all());
  • Pro Tip: Use ray()->table($data) for tabular data (e.g., query results).

2. Query Debugging

Log raw SQL or Eloquent queries:

ray()->query($query); // Logs the query and its bindings
ray()->sql($query->toSql(), $query->getBindings()); // Manual SQL logging
  • Integration: Add to a middleware or service provider to log all queries:
    app()->booted(function () {
        \Spatie\Ray\Ray::captureQueries();
    });
    

3. Performance Measurement

Use ray()->measure() to track execution time:

ray()->measure('Process order', function () {
    // Code to measure
    Order::find($id)->process();
});
  • Global Measurement: Wrap routes or controllers:
    ray()->measure('User profile load', function () {
        return view('profile', ['user' => User::find(1)]);
    });
    

4. Blade Debugging

Add @ray directives in views:

@ray($user) <!-- Logs the $user variable -->
@ray('Current route', route()->current())
  • Advanced: Use @xray to log all Blade variables:
    @xray
    

5. Exception Context

Enhance error logs with additional context:

try {
    // Risky code
} catch (\Exception $e) {
    ray()->exception($e, [
        'user_id' => auth()->id(),
        'request_data' => $request->all(),
    ]);
    throw $e;
}

6. Email Debugging

Log outgoing emails (works with any mail driver):

ray()->mail($mailable); // Logs the raw email content
  • Auto-Capture: Enable in config/ray.php:
    'mail' => true,
    

7. Conditional Logging

Use Ray’s context to filter logs:

ray()->withContext(['user_id' => auth()->id()])->info('User action');
  • Filter in Ray: Use the context filter in the UI to show only relevant logs.

Integration Tips

Middleware Integration

Log requests/responses globally:

public function handle($request, Closure $next)
{
    ray()->info('Incoming request', [
        'method' => $request->method(),
        'path' => $request->path(),
    ]);

    $response = $next($request);

    ray()->info('Response', [
        'status' => $response->status(),
        'headers' => $response->headers->all(),
    ]);

    return $response;
}

Event Listeners

Log events with context:

public function handle(OrderPlaced $event)
{
    ray()->event($event, [
        'user' => $event->user,
        'total' => $event->order->total,
    ]);
}

Testing

Mock Ray in tests to avoid clutter:

public function testSomething()
{
    Ray::shouldReceive('info')->once();
    // Test code
}

CI/CD

Disable Ray in production by setting:

RAY_ENABLED=false

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Issue: Excessive ray() calls can slow down development.
    • Fix: Use conditionally (e.g., only in APP_DEBUG mode):
      if (app()->environment('local')) {
          ray('Debug data', $data);
      }
      
    • Pro Tip: Use ray()->debug() for local-only logs.
  2. Sensitive Data Leaks:

    • Issue: Accidentally logging passwords, tokens, or PII.
    • Fix: Sanitize data before logging:
      ray('User', [
          'id' => $user->id,
          'email' => $user->email,
          // Omit sensitive fields
      ]);
      
    • Ray Feature: Use ray()->mask() to redact sensitive values:
      ray()->mask('password', $user->toArray());
      
  3. Query Logging Overhead:

    • Issue: captureQueries() can impact performance.
    • Fix: Enable only when needed:
      if ($request->has('debug')) {
          Ray::captureQueries();
      }
      
  4. Blade @ray in Production:

    • Issue: @ray directives may expose data in production.
    • Fix: Disable Blade debugging in production:
      'blade' => [
          'enabled' => env('APP_DEBUG', false),
      ],
      
  5. Ray App ID Mismatch:

    • Issue: Logs not appearing in Ray.
    • Fix: Verify RAY_APP_ID in .env matches the one in the Ray app settings.
  6. Large Payloads:

    • Issue: Logging large arrays or files may crash Ray.
    • Fix: Limit data size or use ray()->file() for large content:
      ray()->file(storage_path('logs/large-data.log'));
      

Debugging Tips

  1. Ray Not Receiving Logs:

    • Check if the Ray app is running and connected to the correct RAY_APP_ID.
    • Verify the Laravel app is running and the Ray service provider is registered (check config/app.php under providers).
  2. Logs Not Formatting Correctly:

    • Ensure all dependencies are up-to-date (composer update spatie/laravel-ray).
    • Clear Ray’s cache with:
      php artisan ray:clean
      
  3. Query Logs Missing:

    • Confirm captureQueries() is called and the database connection is active.
    • Check for errors in storage/logs/laravel.log.
  4. Blade @ray Not Working:

    • Ensure the Blade compiler is running (php artisan view:clear).
    • Verify the @ray directive is not inside a @once or @stack directive.

Extension Points

  1. Custom Loggers: Extend Ray’s functionality by creating custom loggers:

    Ray::extend('custom', function ($message, $data = []) {
        // Custom logic
        return [
            'type' => 'custom',
            'message' => $message,
            'data' => $data,
        ];
    });
    

    Use it like:

    ray()->custom('My message', ['key' => 'value']);
    
  2. Ray Directives: Add custom directives to the RayServiceProvider:

    public function boot()
    {
        Ray::directive('measure', function ($name, $callable) {
            $start = microtime(true);
            $result = $callable();
            $duration = microtime(true) - $start;
            return [
                'type' => 'measure',
                'name' => $name,
                'duration' => $duration,
                'result' => $result,
            ];
        });
    }
    

    Use in Blade:

    @measure('Load data', App\DataLoader::fetch())
    
  3. Ray Middleware: Create middleware to log specific request/response data:

    public function handle($request, Closure $next)
    {
        ray()->info('API Request', [
            'headers' => $request->header(),
            'input' => $request->all(),
        ]);
    
        return $next($request);
    }
    
  4. Ray Commands: Extend the `ray:

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