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

Craft Ray Laravel Package

spatie/craft-ray

Send debug output from Craft CMS to Ray, Spatie’s desktop debugging app. Inspect arrays, HTML, queries, and more with a consistent API, measure performance, and pause execution. Great for fast feedback across PHP and other languages.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require spatie/craft-ray
    

    Add to your composer.json under require-dev if needed.

  2. Configure Ray

    • Publish the config file:
      php craft ray:install
      
    • Update .env with your Ray API key (from myray.app).
      RAY_API_KEY=your_api_key_here
      
  3. First Debug Output Use ray() helper in your templates or PHP files:

    // In a controller or service
    ray('Debugging this value:', $someVariable);
    
    // In a Twig template
    {{ ray('Template variable:', entry) }}
    
  4. Start Ray Launch the Ray desktop app and ensure it’s connected to your Craft project.


First Use Case: Debugging a Plugin

  • Scenario: Debugging a custom plugin’s logic during development.
  • Steps:
    1. Add ray() calls in your plugin’s init() or service methods.
    2. Trigger the plugin’s functionality (e.g., via a test entry save).
    3. View real-time output in Ray, including:
      • Variable dumps (arrays, objects).
      • SQL queries (if logged via Craft::$app->getDb()->enableProfiling).
      • Error traces.

Implementation Patterns

Core Workflows

1. Debugging Twig Templates

  • Replace {{ dump(entry) }} with {{ ray(entry) }} for persistent, interactive output.
  • Example:
    {% set filteredEntries = craft.entries()
      .section('blog')
      .limit(5)
      .all()
    %}
    {{ ray('Filtered entries:', filteredEntries) }}
    

2. Logging Queries and Performance

  • Enable query logging in config/ray.php:
    'log_queries' => true,
    
  • Use ray() with Craft::$app->getDb()->createCommand():
    $query = Craft::$app->getDb()->createCommand('SELECT * FROM {{%entries}} WHERE ...');
    ray('SQL Query:', $query->rawSql);
    

3. Conditional Debugging

  • Wrap ray() in environment checks (e.g., APP_DEBUG):
    if (Craft::$app->getConfig()->getGeneral()->devMode) {
        ray('Dev-only data:', $devData);
    }
    

4. Integrating with Events

  • Debug event payloads in onBeforeSave or onAfterSave:
    Event::on(
        Entry::class,
        Entry::EVENT_AFTER_SAVE,
        function (Event $event) {
            ray('Saved entry:', $event->sender);
        }
    );
    

5. Markdown and HTML Output

  • Format complex data for readability:
    ray('## User Data', [
        'name' => $user->name,
        'permissions' => $user->getPermissions(),
    ], 'markdown');
    

Integration Tips

  • Ray with Craft’s debug(): Redirect Craft::debug() output to Ray by extending the package or using a wrapper:

    function craftRayDebug($var, $label = null) {
        if (Craft::$app->getConfig()->getGeneral()->devMode) {
            ray($label ?? 'Debug:', $var);
        }
    }
    
  • Ray in CLI Commands: Use ray() in craft console commands for real-time debugging:

    public function actionTest()
    {
        $data = $this->someLogic();
        ray('CLI Data:', $data);
    }
    
  • Ray Themes: Customize Ray’s appearance in config/ray.php:

    'theme' => 'dark', // or 'light', 'custom'
    

Gotchas and Tips

Pitfalls

  1. API Key Leaks:

    • Never commit .env or config/ray.php with the API key to version control.
    • Use environment variables or a secure secrets manager.
  2. Performance Overhead:

    • Disable ray() in production by wrapping calls in APP_DEBUG checks.
    • Avoid logging large datasets (e.g., entire entry collections) in loops.
  3. Query Logging:

    • Enabling log_queries can slow down Craft. Use sparingly in development.
  4. Ray App Connection:

    • Ensure the Ray app is running and connected to the correct Craft project (check the project name in Ray’s settings).
  5. Twig Caching:

    • If using Twig caching, {{ ray() }} may not appear until the cache is cleared. Test in dev mode (craft config/dev-mode true).

Debugging Tips

  • Missing Output?

    • Verify the Ray app is open and connected to the correct project.
    • Check storage/logs/craft.log for errors (e.g., invalid API key).
  • Slow Ray Responses:

    • Large payloads (e.g., nested arrays) may lag. Simplify data or use ray()->ignore() for specific properties:
      ray($user)->ignore(['passwordHash', 'apiTokens']);
      
  • SQL Queries Not Showing:

    • Ensure log_queries is true in config/ray.php and that you’re using ray() with query objects, not raw SQL strings.
  • Custom Data Types:

    • Ray may not format Craft-specific objects (e.g., Element, Category) by default. Extend the package or cast to arrays:
      ray('Element data:', (array) $entry);
      

Extension Points

  1. Custom Ray Handlers:

    • Extend the package to add Craft-specific formatters. Example:
      // In a service provider
      Ray::extend(function ($ray) {
          $ray->macro('craftElement', function ($element) {
              return $ray->ray((array) $element);
          });
      });
      
      Usage:
      ray()->craftElement($entry);
      
  2. Ray Middleware:

    • Create a middleware to log requests/responses:
      public function handle($request, Closure $next)
      {
          $response = $next($request);
          ray('Request:', $request->all());
          ray('Response:', $response->getContent());
          return $response;
      }
      
  3. Ray in Tests:

    • Mock Ray in PHPUnit to avoid API calls:
      $this->mock(Ray::class)->shouldReceive('ray')->once();
      
  4. Ray for AI Integration:

    • Use Ray’s MCP server to send AI-generated debug output to Ray for review:
      ray('AI Response:', $aiOutput, 'markdown', ['mcp' => 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.
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