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

shelfwood/laravel-n8n

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require shelfwood/laravel-n8n
    php artisan vendor:publish --tag=n8n-config
    

    Configure .env with N8N_URL and N8N_API_KEY.

  2. First Use Case:

    • Create a Laravel event with the HasN8nTrigger trait:
      use Shelfwood\N8n\Traits\HasN8nTrigger;
      
      class UserRegistered
      {
          use HasN8nTrigger;
          // ...
      }
      
    • Dispatch the event normally:
      event(new UserRegistered($user));
      
    • The package auto-generates a tag (app:user-registered) and sends the payload to n8n.
  3. n8n Setup:

    • In your n8n instance, create a workflow with a Webhook trigger.
    • Tag the workflow with app:user-registered (or the auto-generated tag).
    • Test by firing the Laravel event—n8n should receive the payload.

Implementation Patterns

Core Workflows

  1. Event-Driven Integration:

    • Use HasN8nTrigger on all relevant events (e.g., OrderCreated, PaymentFailed).
    • Example:
      class InvoiceGenerated
      {
          use HasN8nTrigger;
      
          public function __construct(public string $invoiceId) {}
          public function toArray(): array { return ['invoice_id' => $this->invoiceId]; }
      }
      
    • Pattern: Group related events under a shared prefix (e.g., app:account-*) for n8n workflow organization.
  2. Payload Customization:

    • Override toArray() to shape data for n8n:
      public function toArray(): array {
          return [
              'user' => $this->user->toJson(),
              'metadata' => ['source' => 'web'],
          ];
      }
      
    • Tip: Use Laravel’s Arrayable or Jsonable interfaces for consistency.
  3. Conditional Dispatching:

    • Skip n8n for specific events by overriding shouldDispatchToN8n():
      public function shouldDispatchToN8n(): bool {
          return config('n8n.skip_in_dev') || $this->isTestMode;
      }
      
  4. Bulk Events:

    • Dispatch multiple events in a loop (e.g., for batch processing):
      foreach ($orders as $order) {
          event(new OrderProcessed($order));
      }
      
    • Caveat: Ensure n8n can handle the volume (rate-limiting may apply).
  5. Webhook Validation:

    • Use n8n’s Webhook Validation node to verify payloads match expected schemas.
    • Laravel Side: Add a middleware to validate incoming n8n responses if needed.

Integration Tips

  1. Environment Awareness:

    • Disable n8n dispatch in config/n8n.php for local/dev:
      'enabled' => env('APP_ENV') !== 'local',
      
    • Or dynamically:
      public function shouldDispatchToN8n(): bool {
          return app()->environment(['staging', 'production']);
      }
      
  2. Error Handling:

    • Log failed dispatches in AppServiceProvider:
      N8n::failed(function ($event, $exception) {
          Log::error("n8n dispatch failed for {$event::class}", [
              'exception' => $exception,
              'payload' => $event->toArray(),
          ]);
      });
      
  3. Testing:

    • Mock n8n responses in tests:
      N8n::shouldReceive('dispatch')
          ->once()
          ->andReturn(true);
      
    • Use Http::fake() to verify webhook calls:
      Http::fake([
          'your-n8n-instance.com' => Http::response([], 200),
      ]);
      
  4. Dynamic Tags:

    • Generate tags programmatically:
      class OrderShipped
      {
          use HasN8nTrigger;
      
          public function getN8nTag(): string {
              return "app:order-shipped:{$this->orderId}";
          }
      }
      
    • Use Case: Route events to workflows based on dynamic IDs (e.g., app:user-*-activity).
  5. Payload Enrichment:

    • Attach metadata like user context:
      public function toArray(): array {
          return array_merge([
              'user_id' => auth()->id(),
              'ip_address' => request()->ip(),
          ], $this->defaultPayload());
      }
      

Gotchas and Tips

Pitfalls

  1. Tag Mismatches:

    • Issue: n8n workflows aren’t triggered because tags don’t match.
    • Debug: Verify the auto-generated tag (app:class-name-snake) matches the n8n workflow tag.
    • Fix: Override getN8nTag() or ensure n8n tags are lowercase/snake_case.
  2. Payload Size Limits:

    • Issue: Large payloads (e.g., nested objects) may fail n8n’s webhook limits (~10MB).
    • Fix: Flatten data or use toJson() with JSON_UNESCAPED_UNICODE:
      public function toArray(): array {
          return json_decode($this->rawData, true);
      }
      
  3. Rate Limiting:

    • Issue: Rapid event firing (e.g., in loops) may hit n8n’s rate limits.
    • Fix: Add a queue delay:
      event(new LargeBatchProcessed($data))->delay(now()->addSeconds(5));
      
  4. Circular Dependencies:

    • Issue: n8n workflows triggering Laravel events back to n8n creates loops.
    • Fix: Add a processed_at field to events and skip if recently processed.
  5. API Key Exposure:

    • Issue: Hardcoding N8N_API_KEY in .env may not be secure for shared environments.
    • Fix: Use Laravel’s env() with a fallback or a dedicated secrets manager.
  6. Timeouts:

    • Issue: Slow n8n responses may timeout Laravel’s HTTP client.
    • Fix: Increase timeout in config/n8n.php:
      'timeout' => 30, // seconds
      

Debugging Tips

  1. Log Payloads:

    • Enable debug logging in config/n8n.php:
      'log_payloads' => true,
      
    • Check storage/logs/laravel-n8n.log.
  2. Verify Webhook URLs:

    • Ensure n8n workflows use the correct webhook URL (e.g., https://your-n8n-instance.com/webhook/123).
    • Tip: Use n8n’s Webhook Test node to validate URLs.
  3. Check n8n Execution:

    • Monitor n8n’s Execution List for failed workflows.
    • Error: 401 Unauthorized → API key or URL is wrong.
    • Error: 404 Not Found → Webhook URL mismatch.
  4. Payload Validation:

    • Use n8n’s Function Node to log incoming payloads:
      $input.all()
      
    • Compare with Laravel’s toArray() output.
  5. Queue Monitoring:

    • If using queues, check jobs table for stuck N8nDispatchJob records.
    • Fix: Retry manually or adjust queue worker settings.

Extension Points

  1. Custom Dispatch Logic:

    • Override dispatchToN8n() to add pre/post-processing:
      protected function dispatchToN8n(): void {
          $this->enrichPayload();
          parent::dispatchToN8n();
      }
      
  2. Multiple n8n Instances:

    • Extend the package to support multi-tenancy:
      N8n::setInstance('staging', 'https://staging-n8n.com', 'key-staging');
      N8n::dispatch($event, 'staging');
      
  3. Webhook Signatures:

    • Add HMAC validation for security:
      // In config/n8n.php
      'validate_signature' => true,
      'signature_key' => env('N8N_SIGNATURE_KEY'),
      
    • Note: Requires n8n to send a X-Signature header.
  4. Event Retries:

    • Implement exponential backoff for failed dispatches:
      N8n::failed(function ($event, $exception) {
          if ($exception instanceof \GuzzleHttp\Exception\ConnectException) {
              $this->retryAfter(10); // seconds
          }
      });
      
  5. Dynamic Webhook URLs:

    • Route events to different n8n workflows based
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver