### Quick Start: Trigger Webhook, List Workflows, Get Execution Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Demonstrates basic usage of the Laravel N8N client. This includes triggering a webhook with a payload, listing all available workflows, and retrieving the status and data of a specific workflow execution. ```php 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'], includeData: true); ``` -------------------------------- ### Install Laravel N8N Package Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Installs the Laravel N8N package using Composer. This is the initial step to integrate n8n functionality into your Laravel application. Service providers and facades are automatically discovered. ```bash composer require kayedspace/laravel-n8n ``` -------------------------------- ### Extending N8n Client with Custom Macros in PHP Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Illustrates how to extend the N8n client's API classes with custom macros. This example adds a `findByName` method to the `Workflows` class for easier retrieval of workflows by their name. The macro is registered in a service provider. ```php // In a service provider use KayedSpace\N8n\Client\Api\Workflows; Workflows::macro('findByName', function (string $name) { $workflows = $this->list(['name' => $name]); return $workflows[0] ?? null; }); // Usage $workflow = N8nClient::workflows()->findByName('My Workflow'); ``` -------------------------------- ### Apply Custom Middleware to API Requests Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Explains how to apply custom middleware to API requests using the `middleware()` method. This allows you to modify the request client, for example, by adding custom headers, before the request is sent. ```php N8nClient::workflows() ->middleware(fn($client) => $client->withHeaders(['X-Custom' => 'value'])) ->list(); ``` -------------------------------- ### Polling for Execution Completion in PHP Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Shows how to poll for the completion of an N8n execution using the N8nClient. This example specifies a maximum timeout of 60 seconds and an interval of 2 seconds between polling attempts. It returns the execution object upon completion. ```php // Wait for execution to complete (max 60s, poll every 2s) $execution = N8nClient::executions()->wait($executionId, timeout: 60, interval: 2); ``` -------------------------------- ### GET /variables - All Variables Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieves all variables, automatically handling pagination to return all available data. ```APIDOC ## GET /variables ### Description Auto-paginate and retrieve all variables. ### Method GET ### Endpoint /variables ### Parameters #### Query Parameters - **filters** (object, optional) - Filters to apply to the variable retrieval. (Specific filter fields depend on implementation). ### Response #### Success Response (200) - **data** (array) - An array of all variable objects. - **id** (string) - The unique identifier of the variable. - **key** (string) - The key of the variable. - **value** (any) - The value of the variable. #### Response Example ```json { "data": [ {"id": "var_abc123", "key": "ENV_MODE", "value": "production"}, {"id": "var_xyz789", "key": "API_URL", "value": "https://api.example.com"}, {"id": "var_pqr456", "key": "DEBUG_MODE", "value": "false"} ] } ``` ``` -------------------------------- ### Manage n8n Users API - PHP Source: https://context7.com/kayedspace/laravel-n8n/llms.txt This section details user management in n8n via the KayedSpace N8n client for PHP. It illustrates listing users with optional role and project filtering, creating new users with specified roles, retrieving users by ID or email, changing user roles, and deleting users. Ensure the N8n client is installed. ```php use KayedSpace\N8n\Facades\N8nClient; // List users $users = N8nClient::users()->list([ 'limit' => 50, 'includeRole' => true, 'projectId' => 'proj_123' ]); // Create users (expects array of user objects) $result = N8nClient::users()->create([ [ 'email' => 'user1@example.com', 'firstName' => 'John', 'lastName' => 'Doe', 'role' => 'member' ], [ 'email' => 'user2@example.com', 'firstName' => 'Jane', 'lastName' => 'Smith', 'role' => 'admin' ] ]); // Get user by ID or email $user = N8nClient::users()->get('user@example.com', includeRole: true); // Change user role $result = N8nClient::users()->changeRole('user@example.com', 'admin'); // Available roles: member, admin, owner // Delete user $result = N8nClient::users()->delete('user@example.com'); ``` -------------------------------- ### N8n Event Listeners in Laravel Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Example of how to register event listeners in Laravel's `EventServiceProvider` to react to N8n-related events. This demonstrates listening for workflow creations, execution failures, and rate limit occurrences. ```php // In EventServiceProvider protected $listen = [ WorkflowCreated::class => [ LogWorkflowCreation::class, NotifyTeam::class, ], ExecutionFailed::class => [ SendFailureAlert::class, ], RateLimitEncountered::class => [ LogRateLimit::class, ], ]; ``` -------------------------------- ### Manage N8n Users with PHP Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md This snippet illustrates how to manage users in N8n using the N8nClient in PHP. It includes examples for inviting new users, retrieving all users, fetching users with their roles, and changing a user's role. ```php // Invite users N8nClient::users()->create([ ['email' => 'dev@example.com', 'role' => 'member'] ]); // Get all users $allUsers = N8nClient::users()->all(); // Get users with roles included foreach (N8nClient::users()->listIterator(['includeRole' => true]) as $user) { // Process each user } // Promote to admin N8nClient::users()->changeRole('dev@example.com', 'admin'); ``` -------------------------------- ### Generate Test Data with N8N Factories in Laravel Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Demonstrates the use of test data factories provided by the N8N package for generating realistic test data for workflows, executions, and credentials. Examples include creating active workflows with specific names and tags, and different states of executions. ```php 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(); ``` -------------------------------- ### Create New Workflow Programmatically (PHP) Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Programmatically create a new n8n workflow by defining its name, nodes, connections, settings, and tags. The example demonstrates creating a simple webhook and email sending node. ```php use KayedSpace\N8n\Facades\N8nClient; $workflow = N8nClient::workflows()->create([ 'name' => 'Customer Onboarding Flow', 'active' => false, 'nodes' => [ [ 'id' => 'webhook_node', 'type' => 'n8n-nodes-base.webhook', 'position' => [100, 200], 'parameters' => [ 'path' => 'customer-signup', 'httpMethod' => 'POST' ] ], [ 'id' => 'email_node', 'type' => 'n8n-nodes-base.emailSend', 'position' => [300, 200], 'parameters' => [ 'fromEmail' => 'welcome@company.com', 'toEmail' => '={{ $json.email }}', 'subject' => 'Welcome to Our Platform' ] ] ], 'connections' => [ 'webhook_node' => [ 'main' => [[['node' => 'email_node', 'type' => 'main', 'index' => 0]]] ] ], 'settings' => [ 'executionOrder' => 'v1' ], 'tags' => ['onboarding', 'production'] ]); // Access created workflow data echo "Created workflow ID: {$workflow['id']} "; echo "Workflow name: {$workflow['name']} "; ``` -------------------------------- ### Trigger n8n Webhooks with Various Options (PHP) Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Demonstrates triggering n8n webhooks with different HTTP methods, authentication, and async processing options. It covers default POST requests, GET requests, basic authentication, removing authentication, and queuing requests for asynchronous execution. ```php use KayedSpace\N8n\Facades\N8nClient; use KayedSpace\N8n\Enums\RequestMethod; // Trigger webhook with POST (default) $response = N8nClient::webhooks()->request('customer-signup', [ 'email' => 'customer@example.com', 'name' => 'John Doe', 'plan' => 'premium' ]); // Trigger with GET method $response = N8nClient::webhooks(RequestMethod::Get) ->request('status-check', ['id' => 123]); // Custom basic authentication (overrides config) $response = N8nClient::webhooks ->withBasicAuth('custom_user', 'custom_pass') ->request('secure-webhook', $data); // Remove authentication $response = N8nClient::webhooks() ->withoutBasicAuth() ->request('public-webhook', $data); // Async webhook triggering (queued) N8nClient::webhooks() ->async() ->request('long-running-process', $largeDataset); // Returns immediately: ['queued' => true, 'path' => 'long-running-process'] // Force synchronous execution $response = N8nClient::webhooks() ->sync() ->request('immediate-webhook', $data); ``` -------------------------------- ### Handle N8N Specific Exceptions in Laravel Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Provides examples of how to catch and handle domain-specific exceptions thrown by the N8N package. It covers various error types like `WorkflowNotFoundException`, `ExecutionFailedException`, and `RateLimitException`, showing how to access status codes, response objects, and additional context. ```php 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'); } ``` -------------------------------- ### Add New API Resource to N8nClient Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Demonstrates how to create a new API resource class that extends `AbstractApi` and integrates with the `N8nClient`. It shows how to handle pagination, make HTTP requests, and implement methods for specific API operations. ```php class MyResource extends AbstractApi { use HasPagination; // Adds all() and listIterator() methods public function list(array $filters = []): Collection|array { return $this->request(RequestMethod::Get, '/my-resource', $filters); } public function deleteMany(array $ids): array { $results = []; foreach ($ids as $id) { try { $result = $this->delete($id); $results[$id] = ['success' => true, 'data' => $result]; } catch (\Exception $e) { $results[$id] = ['success' => false, 'error' => $e->getMessage()]; } } return $results; } } ``` -------------------------------- ### n8n Response Caching - PHP Source: https://context7.com/kayedspace/laravel-n8n/llms.txt This PHP code demonstrates how to enable and utilize response caching for n8n API calls with the KayedSpace N8n client. Caching is configured in `config/n8n.php` and automatically invalidates on mutations. The snippet shows enabling caching, using cached responses for GET requests, forcing fresh data, and how caching interacts with pagination. Works with GET requests only. ```php use KayedSpace\N8n\Facades\N8nClient; // Enable caching in config/n8n.php // 'cache' => [ // 'enabled' => true, // 'store' => 'redis', // 'ttl' => 300, // 'prefix' => 'n8n' // ] // Use cached responses (GET requests only) $workflows = N8nClient::workflows()->cached()->list(); // Subsequent calls within TTL return cached data // Force fresh data (bypass cache) $workflows = N8nClient::workflows()->fresh()->list(); // Cache is automatically invalidated on mutations N8nClient::workflows()->create($workflowData); // Clears workflow cache N8nClient::workflows()->update('id', $data); // Clears workflow cache N8nClient::workflows()->delete('id'); // Clears workflow cache // Caching works with pagination $allWorkflows = N8nClient::workflows() ->cached() ->all(['active' => true]); // Caches each page ``` -------------------------------- ### Environment Variables for Queue (Async Webhooks) Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Settings for enabling and configuring the queue connection used for asynchronous webhook processing. This allows webhooks to be handled in the background. ```env N8N_QUEUE_ENABLED=false # Enable async webhooks N8N_QUEUE_CONNECTION=default # Queue connection N8N_QUEUE_NAME=default # Queue name ``` -------------------------------- ### Get Workflow Tags Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieve all tags associated with a specific workflow. ```APIDOC ## GET /workflows/{id}/tags ### Description Get all tags associated with the workflow. ### Method GET ### Endpoint /workflows/{id}/tags #### Path Parameters - **id** (string) - Required - The unique identifier of the workflow. ### Response #### Success Response (200) - **tags** (array) - An array of tag objects associated with the workflow. - **id** (string) - The tag ID. - **name** (string) - The tag name. #### Response Example ```json { "tags": [ { "id": "tag_1", "name": "Production" }, { "id": "tag_2", "name": "Urgent" } ] } ``` ``` -------------------------------- ### Paginate All Workflows Automatically Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Shows how to retrieve all workflows, including those beyond the first page, using the `all()` method. This method handles the pagination logic internally, simplifying the process of fetching large datasets. ```php // Auto-paginate all items $allWorkflows = N8nClient::workflows()->all(['active' => true]); ``` -------------------------------- ### Async and Sync Webhook Requests in PHP Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Demonstrates how to send asynchronous and synchronous webhook requests using the N8nClient. The async method queues the webhook for background processing, while sync sends it immediately. Both methods require the webhook endpoint and payload data. ```php // Queue webhook trigger N8nClient::webhooks()->async()->request('/my-webhook', $data); // Synchronous (default) N8nClient::webhooks()->sync()->request('/my-webhook', $data); ``` -------------------------------- ### Get All Executions (Auto-Paginated) Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Auto-paginate and retrieve all executions matching the specified filters. ```APIDOC ## GET /executions (Auto-Paginated) ### Description Auto-paginate and retrieve all executions matching the specified filters. This is a convenience method that handles pagination automatically. ### Method GET ### Endpoint /executions ### Query Parameters - **workflowId** (string) - Optional - Filter by workflow ID. - **status** (string) - Optional - Filter by execution status. ### Request Example ```json { "workflowId": "wf1" } ``` ### Response #### Success Response (200) - **data** (array) - An array of all execution objects matching the filters. #### Response Example ```json { "data": [ { "id": 101, "workflowId": "wf1", "status": "success", "created_at": "2023-10-27T10:00:00Z" }, { "id": 102, "workflowId": "wf1", "status": "failed", "created_at": "2023-10-27T10:05:00Z" } ] } ``` ``` -------------------------------- ### Get Workflow Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieve a specific workflow by its ID. Optionally exclude pinned node data. ```APIDOC ## GET /workflows/{id} ### Description Retrieve a specific workflow by its ID. ### Method GET ### Endpoint /workflows/{id} #### Path Parameters - **id** (string) - Required - The unique identifier of the workflow. #### Query Parameters - **excludePinnedData** (boolean) - Optional - If true, exclude pinned node data. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the workflow. - **name** (string) - The name of the workflow. - **nodes** (array) - An array of node definitions. - **connections** (array) - An array of connection definitions. #### Response Example ```json { "id": "wf_abc123", "name": "My Workflow", "nodes": [...], "connections": [...] } ``` ``` -------------------------------- ### List and Manage n8n Workflows Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Provides commands to list workflows, with options to filter by activation status and limit the results. It also allows for activating and deactivating specific workflows using their IDs. ```bash # List workflows php artisan n8n:workflows:list --limit=20 --active=true # Activate/deactivate workflows php artisan n8n:workflows:activate {workflow-id} php artisan n8n:workflows:deactivate {workflow-id} ``` -------------------------------- ### GET /variables - List Iterator Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Provides a memory-efficient generator for iterating through all variables, ideal for large datasets. ```APIDOC ## GET /variables ### Description Memory-efficient generator for iterating through all variables. ### Method GET ### Endpoint /variables ### Parameters #### Query Parameters - **filters** (object, optional) - Filters to apply to the variable retrieval. (Specific filter fields depend on implementation). ### Response This endpoint typically returns a generator or stream of variable objects, rather than a JSON array in a single response. The exact format depends on the client implementation but conceptually yields individual variable objects. ### Conceptual Iteration Example (pseudo-code) ```python # Assuming a client library method that returns an iterator variable_iterator = n8n_client.variables().list_iterator() for variable in variable_iterator: print(f"ID: {variable['id']}, Key: {variable['key']}, Value: {variable['value']}") ``` ### Conceptual Response Body (per item) ```json { "id": "var_abc123", "key": "ENV_MODE", "value": "production" } ``` ``` -------------------------------- ### Iterate Through Workflows with Iterator Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Demonstrates a memory-efficient way to process workflows one by one using `listIterator()`. This is ideal for handling large numbers of workflows without loading them all into memory simultaneously. ```php // Memory-efficient iterator foreach (N8nClient::workflows()->listIterator() as $workflow) { // Process one at a time } ``` -------------------------------- ### Executions API - List and Get Executions Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Retrieve execution history with filtering options and detailed execution data including workflow results. ```APIDOC ## Executions API - List and Get Executions ### Description Retrieve execution history with filtering options and detailed execution data including workflow results. ### Method GET ### Endpoint `/executions` `/executions/{execution_id}` ### Parameters #### Path Parameters - **execution_id** (integer) - Required - The ID of the execution to retrieve details for. #### Query Parameters - **workflowId** (string) - Optional - Filter executions by workflow ID. - **status** (string) - Optional - Filter executions by status (e.g., 'success', 'error', 'failed', 'crashed', 'waiting', 'running'). - **includeData** (boolean) - Optional - Whether to include the full execution data. Defaults to false. - **limit** (integer) - Optional - The maximum number of executions to return. - **projectId** (string) - Optional - Filter executions by project ID. #### Request Body None for list or get operations. ### Request Example ```php // List all executions $executions = N8nClient::executions()->list(); // Filter executions $executions = N8nClient::executions()->list([ 'workflowId' => 'workflow_id_123', 'status' => 'success', 'includeData' => false, 'limit' => 50, 'projectId' => 'proj_123' ]); // Auto-paginate all executions $allExecutions = N8nClient::executions()->all([ 'workflowId' => 'workflow_id_123', 'status' => 'error' ]); // Get execution details with full data $execution = N8nClient::executions()->get(12345, includeData: true); ``` ### Response #### Success Response (200) - **executions** (array) - An array of execution objects. - Each execution object contains: - **id** (integer) - The execution ID. - **status** (string) - The status of the execution. - **startedAt** (string) - The start time of the execution. - **finishedAt** (string) - The end time of the execution. - **data** (object) - The full workflow execution data (only if `includeData` is true). #### Response Example ```json { "executions": [ { "id": 12345, "status": "success", "startedAt": "2023-10-27T10:00:00Z", "finishedAt": "2023-10-27T10:05:00Z", "data": { "workflow_result": "some data" } } ] } ``` ``` -------------------------------- ### Perform Batch Operations on Workflows Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Shows how to perform batch operations, such as activating multiple workflows simultaneously. The `activateMany()` method takes an array of workflow IDs and returns the results of the operations. ```php // Activate multiple workflows $results = N8nClient::workflows()->activateMany(['id1', 'id2', 'id3']); ``` -------------------------------- ### GET /variables - List Variables Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieves a list of variables, supporting optional pagination via limit and cursor parameters. ```APIDOC ## GET /variables ### Description List variables with optional pagination using limit and cursor. ### Method GET ### Endpoint /variables ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of variables to return. - **cursor** (string) - Optional - A cursor for pagination, indicating the starting point for the next set of results. ### Response #### Success Response (200) - **data** (array) - An array of variable objects. - **id** (string) - The unique identifier of the variable. - **key** (string) - The key of the variable. - **value** (any) - The value of the variable. - **next_cursor** (string, optional) - A cursor to retrieve the next page of results. #### Response Example ```json { "data": [ {"id": "var_abc123", "key": "ENV_MODE", "value": "production"}, {"id": "var_xyz789", "key": "API_URL", "value": "https://api.example.com"} ], "next_cursor": "cursor_string_for_next_page" } ``` ``` -------------------------------- ### Environment Variables for HTTP Client Configuration Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Specifies environment variables to configure the underlying HTTP client used by the N8n client. Options include request timeout, error handling behavior (throwing exceptions), and retry mechanisms with different strategies. ```env N8N_TIMEOUT=120 # Request timeout (seconds) N8N_THROW=true # Throw exceptions on errors N8N_RETRY=3 # Number of retry attempts N8N_RETRY_STRATEGY=exponential # constant, linear, exponential N8N_RETRY_MAX_DELAY=10000 # Max retry delay (ms) ``` -------------------------------- ### Get Execution by ID Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieve detailed information for a specific workflow execution. Optionally include the execution's data. ```APIDOC ## GET /executions/{id} ### Description Retrieve detailed information for a specific workflow execution by its ID. You can optionally include the execution's data payload. ### Method GET ### Endpoint /executions/{id} ### Path Parameters - **id** (integer) - Required - The ID of the execution to retrieve. ### Query Parameters - **includeData** (boolean) - Optional - If true, includes the execution's data payload in the response. ### Request Example ```json { "includeData": true } ``` ### Response #### Success Response (200) - **id** (integer) - The execution ID. - **workflowId** (string) - The ID of the workflow. - **status** (string) - The current status of the execution. - **created_at** (string) - Timestamp of creation. - **updated_at** (string) - Timestamp of last update. - **data** (object) - Optional - The execution's data payload, if `includeData` was true. #### Response Example ```json { "id": 101, "workflowId": "wf1", "status": "success", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:05:00Z", "data": { "input": {}, "output": {"message": "Hello World"} } } ``` ``` -------------------------------- ### Create and Activate Workflow (PHP) Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Demonstrates how to create a new workflow with a given payload and then activate it. Requires the N8nClient to be initialized. ```php // Create and activate a workflow $workflow = N8nClient::workflows()->create([ 'name' => 'My Workflow', 'nodes' => [...], 'connections' => [...], ]); N8nClient::workflows()->activate($workflow['id']); ``` -------------------------------- ### Run Tests with Composer Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Executes the test suite to ensure code changes do not introduce regressions. All contributions should include passing tests. ```bash composer test ``` -------------------------------- ### Webhook Signature Verification Middleware in PHP Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Shows how to protect webhook endpoints using Laravel's middleware. The `VerifyN8nWebhook` middleware handles signature verification automatically. It also provides an example of manual signature verification. ```php // In routes/web.php or api.php Route::post('/n8n/webhook', function (Request $request) { // Webhook data is verified by middleware $data = $request->all(); // Process webhook... })->middleware('n8n.webhook'); // Register middleware in Http/Kernel.php protected $routeMiddleware = [ 'n8n.webhook' => \KayedSpace\N8n\Http\Middleware\VerifyN8nWebhook::class, ]; ``` ```php use KayedSpace\N8n\Client\Webhook\Webhooks; if (Webhooks::verifySignature($request)) { // Valid signature } ``` -------------------------------- ### Environment Variables for Webhook Configuration Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Details environment variables for configuring webhook reception and security. This includes the base URL for webhooks, basic authentication credentials, and a secret key for signature verification. ```env N8N_WEBHOOK_BASE_URL=https://your-n8n-instance.com/webhook N8N_WEBHOOK_USERNAME=username # Basic auth username N8N_WEBHOOK_PASSWORD=password # Basic auth password N8N_WEBHOOK_SIGNATURE_KEY=your_secret_key # For signature verification ``` -------------------------------- ### Get, Update, and Delete n8n Workflows (PHP) Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Manage individual n8n workflows by their ID. This includes retrieving workflow details, updating existing workflows by providing the full definition, and deleting workflows. ```php use KayedSpace\N8n\Facades\N8nClient; // Get workflow by ID $workflow = N8nClient::workflows()->get('workflow_id_123'); // Get workflow without pinned data (smaller response) $workflow = N8nClient::workflows()->get('workflow_id_123', excludePinnedData: true); // Update workflow $updated = N8nClient::workflows()->update('workflow_id_123', [ 'name' => 'Updated Workflow Name', 'active' => true, 'nodes' => $workflow['nodes'], // Must include full definition 'connections' => $workflow['connections'] ]); // Delete workflow $result = N8nClient::workflows()->delete('workflow_id_123'); ``` -------------------------------- ### General Environment Variables Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md General configuration options for the N8n client, including debug mode, the preferred return type for API responses (array or collection), and metrics tracking. ```env N8N_DEBUG=false # Enable debug mode N8N_RETURN_TYPE=collection # collection or array N8N_METRICS_ENABLED=false # Enable metrics tracking N8N_METRICS_STORE=default # Metrics cache store ``` -------------------------------- ### Force Fresh Workflow Data Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Illustrates how to bypass the cache and fetch fresh data for a specific workflow. The `fresh()` method ensures that the latest information is retrieved directly from the n8n API. ```php // Force fresh data $workflow = N8nClient::workflows()->fresh()->get($id); ``` -------------------------------- ### Delete Executions with N8n PHP Client Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Remove N8n execution records, either individually or in batches. This is useful for managing storage and keeping the execution history clean. The code provides examples for deleting a single execution or multiple executions at once. ```php use KayedSpace\N8n\Facades\N8nClient; // Delete single execution $result = N8nClient::executions()->delete(12345); // Batch delete executions $results = N8nClient::executions()->deleteMany([12345, 12346, 12347]); foreach ($results as $executionId => $result) { if ($result['success']) { echo "Deleted execution: {$executionId} "; } else { echo "Failed to delete {$executionId}: {$result['error']} "; } } ``` -------------------------------- ### N8n Project Management via PHP Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Demonstrates creating, retrieving, updating, and deleting projects in N8n. It also shows how to manage users within projects, including adding and changing roles. This functionality relies on the N8nClient library. ```php // 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']); ``` -------------------------------- ### Track API Usage Metrics in Cache (PHP) Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md This snippet demonstrates how to track API usage metrics, such as total requests and average duration, which are automatically stored in the cache. It shows how to retrieve these metrics using the cache store, prefixed with a date and hour. ```php // Metrics are automatically stored in cache // Access via cache store $totalRequests = Cache::get('n8n:metrics:'.date('Y-m-d-H').':total'); $avgDuration = Cache::get('n8n:metrics:'.date('Y-m-d-H').':duration'); ``` -------------------------------- ### Get Specific Execution Details (PHP) Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieves detailed information for a single workflow execution identified by its ID. An optional parameter allows for including the execution's data payload. This is useful for inspecting the specifics of a single run. ```php // Get detailed execution data $execution = N8nClient::executions()->get(101, includeData: true); ``` -------------------------------- ### Batch Activate Workflows (PHP) Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Illustrates how to activate multiple workflows simultaneously by providing an array of workflow IDs. The results indicate success or failure for each ID. ```php // Batch activate $results = N8nClient::workflows()->activateMany(['wf1', 'wf2', 'wf3']); ``` -------------------------------- ### Manage n8n Credentials (Create, List, Get, Delete) (PHP) Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Illustrates how to manage n8n credentials using the laravel-n8n package. This includes creating new credentials with specific types and data, listing all credentials, retrieving individual credential details, and deleting credentials. ```php use KayedSpace\N8n\Facades\N8nClient; // Create credential $credential = N8nClient::credentials()->create([ 'name' => 'My API Credential', 'type' => 'httpBasicAuth', 'data' => [ 'user' => 'api_user', 'password' => 'secure_password' ] ]); // List credentials $credentials = N8nClient::credentials()->list(); // Get credential details $credential = N8nClient::credentials()->get('cred_id_123'); // Get credential schema/definition $schema = N8nClient::credentials()->schema('httpBasicAuth'); print_r($schema); // Shows required fields and structure // Delete credential $result = N8nClient::credentials()->delete('cred_id_123'); // Transfer credential to another project $result = N8nClient::credentials()->transfer( 'cred_id_123', 'destination_project_id' ); ``` -------------------------------- ### Manage n8n via Artisan Commands - Bash Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Provides a set of Artisan commands for managing n8n services directly from the command line. These commands include checking n8n instance health, listing workflows with filtering options, activating or deactivating workflows, checking the status of workflow executions, and testing webhook triggers with custom data. ```bash # Check n8n instance health and connectivity php artisan n8n:health # List workflows with filters php artisan n8n:workflows:list php artisan n8n:workflows:list --limit=50 --active=true # Activate workflow php artisan n8n:workflows:activate workflow_id_123 # Deactivate workflow php artisan n8n:workflows:deactivate workflow_id_123 # Check execution status php artisan n8n:executions:status 12345 # Test webhook trigger php artisan n8n:test-webhook customer-signup --data='{"email":"test@example.com"}' ``` -------------------------------- ### Get All Workflow Executions (PHP) Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Retrieves all workflow executions that match the provided filters by automatically handling pagination. This method is convenient for fetching all relevant executions without manual cursor management. It requires specifying at least one filter, such as workflowId. ```php // Get all executions (auto-paginate) $allExecutions = N8nClient::executions()->all(['workflowId' => 'wf1']); ``` -------------------------------- ### Environment Variables for Rate Limiting Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Configures how the N8n client handles rate limiting. Enables automatic waiting for rate limit responses (HTTP 429) and sets a maximum wait time. ```env N8N_RATE_LIMIT_AUTO_WAIT=true # Auto-wait on 429 responses N8N_RATE_LIMIT_MAX_WAIT=60 # Max wait time (seconds) ``` -------------------------------- ### Run All Tests with Pest Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Executes all unit and feature tests defined in the project using the Pest testing framework. This command ensures that the codebase remains stable and that new changes do not introduce regressions. ```bash # Run all tests composer test # or vendor/bin/pest ``` -------------------------------- ### List and Get Executions with N8n PHP Client Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Retrieve N8n execution history, with options for filtering and including detailed data. This allows you to monitor workflow runs and diagnose issues. You can list all executions, filter by workflow, status, or project, and retrieve specific execution details. ```php use KayedSpace\N8n\Facades\N8nClient; // List all executions $executions = N8nClient::executions()->list(); // Filter executions $executions = N8nClient::executions()->list([ 'workflowId' => 'workflow_id_123', 'status' => 'success', // success, error, failed, crashed, waiting, running 'includeData' => false, 'limit' => 50, 'projectId' => 'proj_123' ]); // Auto-paginate all executions $allExecutions = N8nClient::executions()->all([ 'workflowId' => 'workflow_id_123', 'status' => 'error' ]); // Get execution details with full data $execution = N8nClient::executions()->get(12345, includeData: true); echo "Status: {$execution['status']} "; echo "Started: {$execution['startedAt']} "; echo "Finished: {$execution['finishedAt']} "; print_r($execution['data']); // Full workflow execution data ``` -------------------------------- ### Perform N8N Health Checks in Laravel Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Shows how to use the `HealthCheck` class to monitor your n8n instance's connectivity and overall health. It includes examples of checking the health status and retrieving detailed results, as well as mentioning the available Artisan CLI command. ```php 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] ] ] */ ``` -------------------------------- ### Laravel N8N: Build Workflows Programmatically Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Illustrates how to construct n8n workflows dynamically using a fluent Domain Specific Language (DSL). This allows for programmatic creation and management of workflows, including defining triggers, nodes, and activation status. ```php 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(); ``` -------------------------------- ### Environment Variables for Caching Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Configures response caching for N8n API requests. Options include enabling/disabling caching, specifying the cache store, time-to-live (TTL), and a prefix for cache keys. ```env N8N_CACHE_ENABLED=false # Enable response caching N8N_CACHE_STORE=default # Cache store to use N8N_CACHE_TTL=300 # Cache TTL (seconds) N8N_CACHE_PREFIX=n8n # Cache key prefix ``` -------------------------------- ### Manage Credentials with N8n API Client (PHP) Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Provides methods for managing credentials within n8n. This includes creating, listing, retrieving, deleting, and transferring credentials, as well as fetching credential schemas. Requires interaction with the /credentials endpoint via POST, GET, DELETE, and PUT HTTP methods. ```php // 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 credentials with filters // $credentials = N8nClient::credentials()->list(['limit' => 10]); // Get a specific credential by ID // $credential = N8nClient::credentials()->get('some_credential_id'); // Delete a credential // N8nClient::credentials()->delete('some_credential_id'); // Transfer a credential // N8nClient::credentials()->transfer('some_credential_id', 'destination_project_id'); ``` -------------------------------- ### Format Code with Laravel Pint Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Ensures code style consistency by running Laravel Pint. This command should be executed before committing changes to maintain project standards. ```bash composer pint ``` -------------------------------- ### Extend API Resources with Macros Source: https://context7.com/kayedspace/laravel-n8n/llms.txt Leverage Laravel's Macroable trait to add custom methods to n8n API resource classes, such as the Workflows resource. This allows for reusable, domain-specific logic to be encapsulated directly within the client. Macros can be registered in a service provider and then used like any other method on the resource. Examples include finding workflows by name or tag, and retrieving active workflows. ```php use KayedSpace\N8n\Client\Api\Workflows; use KayedSpace\N8n\Facades\N8nClient; // Register macro in service provider Workflows::macro('findByName', function (string $name) { $workflows = $this->all(); return collect($workflows)->firstWhere('name', $name); }); Workflows::macro('activeWorkflows', function () { return $this->list(['active' => true]); }); // Use custom methods $workflow = N8nClient::workflows()->findByName('Customer Onboarding'); $active = N8nClient::workflows()->activeWorkflows(); // Macro with parameters Workflows::macro('findByTag', function (string $tagName) { $workflows = $this->all(); return collect($workflows)->filter(function ($workflow) use ($tagName) { return in_array($tagName, $workflow['tags'] ?? []); }); }); $prodWorkflows = N8nClient::workflows()->findByTag('production'); ``` -------------------------------- ### Test n8n Webhook via Artisan CLI Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Simulates incoming webhook requests to test n8n webhook endpoints. Supports specifying the webhook path and sending custom data payloads. ```bash php artisan n8n:test-webhook {path} php artisan n8n:test-webhook /my-webhook --data='{"key":"value"}' ``` -------------------------------- ### Import Workflow Source: https://github.com/kayedspace/laravel-n8n/blob/main/README.md Import a workflow definition. The payload should contain the complete workflow structure. ```APIDOC ## POST /workflows (Import) ### Description Import a workflow definition. ### Method POST ### Endpoint /workflows #### Request Body - **workflow** (object) - Required - The workflow definition object to import. - **name** (string) - Required - The name of the workflow. - **nodes** (array) - Required - An array of node definitions. - **connections** (array) - Required - An array of connection definitions. ### Request Example ```json { "workflow": { "name": "Imported Workflow", "nodes": [...], "connections": [...] } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the imported workflow. - **name** (string) - The name of the imported workflow. #### Response Example ```json { "id": "wf_imported123", "name": "Imported Workflow" } ``` ``` -------------------------------- ### Check n8n Instance Connectivity Source: https://github.com/kayedspace/laravel-n8n/blob/main/CLAUDE.md Verifies the connectivity between your Laravel application and the n8n instance. This command is useful for ensuring that the n8n API is reachable and that authentication is correctly configured. ```bash # Check n8n instance connectivity php artisan n8n:health ```