PHP code example of kayedspace / laravel-n8n

1. Go to this page and download the library: Download kayedspace/laravel-n8n library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kayedspace / laravel-n8n example snippets


use KayedSpace\N8n\Facades\N8nClient;

// Trigger webhook
$webhookTrigger = N8nClient::webhooks()->request("path-to-webhook", $payload);

// List all workflows
$workflows = N8nClient::workflows()->list();

// Retrieve execution status with data
$status = N8nClient::executions()->get($execution['id'], 

// Trigger a webhook
$response = N8nClient::webhooks()->request("path-to-webhook", $payload);

// Custom basic auth (overrides .env credentials)
$response = N8nClient::webhooks()
    ->withBasicAuth("username", "password")
    ->request("path-to-webhook", $payload);

// Without authentication
$response = N8nClient::webhooks()
    ->withoutBasicAuth()
    ->request("path-to-webhook", $payload);

// Queue the webhook (returns immediately)
N8nClient::webhooks()->async()->request('/my-webhook', $data);

// Force synchronous (default)
N8nClient::webhooks()->sync()->request('/my-webhook', $data);

> Configure queue behaviour via `N8N_QUEUE_ENABLED`, `N8N_QUEUE_CONNECTION`, and `N8N_QUEUE_NAME` in your `.env` file.

// Set signature key in .env: N8N_WEBHOOK_SIGNATURE_KEY=your_secret

// Apply middleware to routes
Route::post('/n8n/webhook', WebhookController::class)
    ->middleware('n8n.webhook');

// Manual verification
use KayedSpace\N8n\Client\Webhook\Webhooks;

if (Webhooks::verifySignature($request)) {
    // Valid signature - process webhook
}

use KayedSpace\N8n\Support\WorkflowBuilder;

$workflow = WorkflowBuilder::create('Customer Onboarding')
    ->trigger('webhook', ['path' => 'customer-created'])
    ->node('httpRequest', [
        'url' => 'https://api.example.com/customer/{{$json.id}}',
        'method' => 'GET',
    ])
    ->node('emailSend', [
        'toEmail' => '{{$json.email}}',
        'subject' => 'Welcome!',
    ])
    ->activate()
    ->saveAndActivate();

// Build without activation
$workflow = WorkflowBuilder::create('Data Pipeline')
    ->trigger('schedule', ['rule' => '0 0 * * *'])
    ->node('httpRequest', ['url' => 'https://api.example.com/data'])
    ->node('set', ['values' => ['processed' => true]])
    ->save();

// Get credential schema
$schema = N8nClient::credentials()->schema('slackApi');

// Create a credential
N8nClient::credentials()->create([
    'name' => 'Slack Token',
    'type' => 'slackApi',
    'data' => [
        'token' => 'xoxb-123456789',
    ]
]);

// Get all credentials
$allCredentials = N8nClient::credentials()->all();

// List executions with pagination
$executions = N8nClient::executions()->list(['status' => 'success', 'limit' => 50]);

// Get all executions (auto-paginate)
$allExecutions = N8nClient::executions()->all(['workflowId' => 'wf1']);

// Memory-efficient iteration
foreach (N8nClient::executions()->listIterator(['status' => 'error']) as $execution) {
    // Process one at a time
}

// Get detailed execution data
$execution = N8nClient::executions()->get(101, 

// Create a project
$project = N8nClient::projects()->create(['name' => 'DevOps', 'description' => 'CI/CD flows']);

// Get all projects
$allProjects = N8nClient::projects()->all();

// Add users
N8nClient::projects()->addUsers($project['id'], [
  ['userId' => 'abc123', 'role' => 'member'],
]);

// Promote user role
N8nClient::projects()->changeUserRole($project['id'], 'abc123', 'admin');

// Delete the project
N8nClient::projects()->delete($project['id']);

$syncStatus = N8nClient::sourceControl()->pull([
    'projectIds' => ['project-1', 'project-2'],
]);

// Create tags
$tag = N8nClient::tags()->create(['name' => 'Marketing']);

// Batch create
$results = N8nClient::tags()->createMany([
    ['name' => 'Production'],
    ['name' => 'Development'],
    ['name' => 'Testing'],
]);

// Get all tags
$allTags = N8nClient::tags()->all();

// Update and delete
N8nClient::tags()->update($tag['id'], ['name' => 'Sales']);
N8nClient::tags()->deleteMany(['tag1', 'tag2']);

// Invite users
N8nClient::users()->create([
  ['email' => '[email protected]', 'role' => 'member']
]);

// Get all users
$allUsers = N8nClient::users()->all();

// Get users with roles ');

// Create a new variable
N8nClient::variables()->create(['key' => 'ENV_MODE', 'value' => 'production']);

// Batch create
$results = N8nClient::variables()->createMany([
    ['key' => 'API_URL', 'value' => 'https://api.example.com'],
    ['key' => 'DEBUG_MODE', 'value' => 'false'],
    ['key' => 'MAX_RETRIES', 'value' => '3'],
]);

// Get all variables
$allVariables = N8nClient::variables()->all();

// Update a variable
N8nClient::variables()->update('ENV_MODE', ['value' => 'staging']);

// Batch delete
N8nClient::variables()->deleteMany(['var1', 'var2', 'var3']);

// Create and activate a workflow
$workflow = N8nClient::workflows()->create([
    'name' => 'My Workflow',
    'nodes' => [...],
    'connections' => [...],
]);
N8nClient::workflows()->activate($workflow['id']);

// Get all active workflows
$activeWorkflows = N8nClient::workflows()->all(['active' => true]);

// Batch activate
$results = N8nClient::workflows()->activateMany(['wf1', 'wf2', 'wf3']);

// Export and import
$exported = N8nClient::workflows()->export('wf1');
$imported = N8nClient::workflows()->import($exported);

// In EventServiceProvider
use KayedSpace\N8n\Events\WorkflowCreated;
use KayedSpace\N8n\Events\WebhookTriggered;

protected $listen = [
    WorkflowCreated::class => [LogWorkflowActivity::class],
    WebhookTriggered::class => [TrackWebhookUsage::class],
];

// config/n8n.php or .env
N8N_EVENTS_ENABLED=true

// Enable in .env
N8N_CACHE_ENABLED=true
N8N_CACHE_TTL=300  // seconds

// Use cached responses
$workflows = N8nClient::workflows()->cached()->list();

// Force fresh data (bypass cache)
$workflow = N8nClient::workflows()->fresh()->get($id);

// config/n8n.php or .env
N8N_METRICS_ENABLED=true
N8N_METRICS_STORE=redis   # Any Laravel cache store

// Enable in .env
N8N_LOGGING_ENABLED=true
N8N_LOGGING_CHANNEL=stack        // Laravel logging channel
N8N_LOGGING_LEVEL=debug          // Logging level
N8N_LOG_REQUEST_BODY=true        // Log request payloads
N8N_LOG_RESPONSE_BODY=true       // Log response data

// Add custom headers
$workflows = N8nClient::workflows()
    ->withClientModifier(function ($client) {
        return $client->withHeaders([
            'X-Custom-Header' => 'value',
            'X-Request-ID' => uniqid(),
        ]);
    })
    ->list();

// Add authentication token
$workflows = N8nClient::workflows()
    ->withClientModifier(function ($client) {
        return $client->withToken('bearer-token');
    })
    ->get($id);

// Add timeout for specific request
$execution = N8nClient::executions()
    ->withClientModifier(function ($client) {
        return $client->timeout(300); // 5 minutes
    })
    ->wait($executionId, timeout: 300);

// Chain multiple modifiers
$response = N8nClient::workflows()
    ->withClientModifier(function ($client) {
        return $client->withHeaders(['X-Tenant-ID' => tenant()->id]);
    })
    ->withClientModifier(function ($client) {
        return $client->retry(5, 1000);
    })
    ->list();

// Add request interceptor for debugging
$workflows = N8nClient::workflows()
    ->withClientModifier(function ($client) {
        return $client->beforeSending(function ($request, $options) {
            logger()->debug('N8N Request', [
                'url' => $request->url(),
                'method' => $request->method(),
            ]);
        });
    })
    ->list();

use KayedSpace\N8n\Client\Api\Workflows;
use KayedSpace\N8n\Facades\N8nClient;

// Register a macro in a service provider
Workflows::macro('findByName', function (string $name) {
    $workflows = $this->list(['name' => $name]);
    return $workflows->firstWhere('name', $name);
});

Workflows::macro('activateAll', function (array $filters = []) {
    $workflows = $this->all($filters);
    $results = [];
    foreach ($workflows as $workflow) {
        $results[] = $this->activate($workflow['id']);
    }
    return $results;
});

// Use the macro
$workflow = N8nClient::workflows()->findByName('My Workflow');
N8nClient::workflows()->activateAll(['tags' => ['production']]);

use KayedSpace\N8n\Exceptions\{
    N8nException,
    WorkflowNotFoundException,
    ExecutionFailedException,
    RateLimitException,
    AuthenticationException,
    ValidationException
};

try {
    $workflow = N8nClient::workflows()->get('invalid-id');
} catch (WorkflowNotFoundException $e) {
    // Handle 404 workflow error
    $statusCode = $e->getCode(); // 404
    $response = $e->getResponse(); // Full response object
    $context = $e->getContext(); // Additional context
}

try {
    $execution = N8nClient::executions()->wait($id, timeout: 30);
} catch (ExecutionFailedException $e) {
    // Handle failed/crashed execution
    logger()->error('Execution failed', [
        'id' => $id,
        'message' => $e->getMessage(),
    ]);
}

try {
    $workflows = N8nClient::workflows()->list();
} catch (RateLimitException $e) {
    // Handle rate limiting
    $retryAfter = $e->getRetryAfter(); // Seconds to wait
    sleep($retryAfter);
}

try {
    $users = N8nClient::users()->list();
} catch (AuthenticationException $e) {
    // Handle 401/403 errors
    logger()->alert('N8N authentication failed');
}

use KayedSpace\N8n\Support\HealthCheck;

$health = HealthCheck::run();

if ($health->isHealthy()) {
    echo "All systems operational";
}

// Get detailed results
$results = $health->toArray();
/*
[
    'overall_status' => 'healthy',
    'checks' => [
        'connectivity' => ['status' => 'pass', 'duration_ms' => 45],
        'api_response' => ['status' => 'pass', 'duration_ms' => 120],
        'workflows' => ['status' => 'pass', 'count' => 15],
        'metrics' => ['workflows' => 15, 'active_workflows' => 8]
    ]
]
*/

use KayedSpace\N8n\Testing\N8nFake;

// Setup fake
N8nFake::fake();

// Queue custom responses
N8nFake::workflows([
    'data' => [
        ['id' => 'wf1', 'name' => 'Test Workflow', 'active' => true]
    ]
]);

// Your application code
$workflows = N8nClient::workflows()->list();

// Assertions
N8nFake::assertWorkflowCreated();
N8nFake::assertWorkflowActivated('wf1');
N8nFake::assertWebhookTriggered('/my-webhook');
N8nFake::assertSentCount(3);

// Custom assertions
N8nFake::assertSent(function ($request) {
    return $request['method'] === 'POST'
        && str_contains($request['url'], '/workflows');
});

N8nFake::assertNotSent(function ($request) {
    return $request['method'] === 'DELETE';
});

use KayedSpace\N8n\Testing\Factories\{WorkflowFactory, ExecutionFactory, CredentialFactory};

// Workflow factory
$workflow = WorkflowFactory::make()
    ->active()
    ->withName('Test Workflow')
    ->withTags(['tag1', 'tag2'])
    ->build();

// Execution factory
$execution = ExecutionFactory::make()
    ->success()
    ->withWorkflow('wf1')
    ->withData(['result' => 'success'])
    ->build();

$failedExecution = ExecutionFactory::make()
    ->failed()
    ->build();

$runningExecution = ExecutionFactory::make()
    ->running()
    ->build();

// Credential factory
$credential = CredentialFactory::make()
    ->withType('slackApi')
    ->withName('My Slack')
    ->withData(['token' => 'xoxb-123'])
    ->build();
bash
php artisan vendor:publish --tag=n8n-config
bash
php artisan n8n:health
bash
# Health check
php artisan n8n:health

# List workflows
php artisan n8n:workflows:list
php artisan n8n:workflows:list --limit=50
php artisan n8n:workflows:list --active=true

# Activate/deactivate workflows
php artisan n8n:workflows:activate {workflow-id}
php artisan n8n:workflows:deactivate {workflow-id}

# Check execution status
php artisan n8n:executions:status {execution-id}

# Test webhook
php artisan n8n:test-webhook {path}
php artisan n8n:test-webhook /my-webhook --data='{"key":"value"}'