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

Influxdb Client Php Laravel Package

influxdata/influxdb-client-php

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require influxdata/influxdb-client-php
    

    Ensure your Laravel project has PHP 8.1+ (required by the package).

  2. Basic Setup Configure the client in config/services.php:

    'influxdb' => [
        'url' => env('INFLUXDB_URL', 'http://localhost:8086'),
        'token' => env('INFLUXDB_TOKEN'),
        'org' => env('INFLUXDB_ORG'),
        'bucket' => env('INFLUXDB_BUCKET'),
    ],
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="InfluxData\InfluxDBClient\InfluxDBClientServiceProvider"
    
  3. First Write Operation Inject the client in a service or controller:

    use InfluxData\InfluxDBClient\InfluxDBClient;
    use InfluxData\InfluxDBClient\Domain\Write\Point;
    
    public function __construct(private InfluxDBClient $client) {}
    
    public function logMetric(string $measurement, array $tags, array $fields) {
        $point = Point::measurement($measurement)
            ->tag($tags)
            ->floatField('value', $fields['value'])
            ->timestamp(time(), WritePrecision::S);
    
        $this->client->getWriteApi()->writePoint($point);
    }
    
  4. First Query Use the query API to fetch data:

    $queryApi = $this->client->getQueryApi();
    $result = $queryApi->query('from(bucket:"my-bucket") |> range(start: -1h)');
    foreach ($result as $row) {
        // Process rows
    }
    

Implementation Patterns

Common Workflows

  1. Structured Logging Use a facade or service to abstract writes:

    // app/Services/MetricsLogger.php
    class MetricsLogger {
        public function __construct(private InfluxDBClient $client) {}
    
        public function log(string $measurement, array $data) {
            $point = Point::measurement($measurement)
                ->addTags($data['tags'] ?? [])
                ->addFields($data['fields']);
    
            $this->client->getWriteApi()->writePoint($point);
        }
    }
    

    Call from anywhere:

    $logger->log('api_requests', [
        'tags' => ['endpoint' => '/users'],
        'fields' => ['duration_ms' => 150, 'status' => 200],
    ]);
    
  2. Batch Writes For high-throughput scenarios, use batch writes:

    $writeApi = $this->client->getWriteApi();
    $writeApi->writePoint($point1);
    $writeApi->writePoint($point2);
    $writeApi->flush(); // Force sync write
    
  3. Query Caching Cache frequent queries (e.g., dashboards) in Laravel’s cache:

    $cacheKey = 'influx_query_dashboard';
    $result = Cache::remember($cacheKey, now()->addMinutes(5), function () {
        return $this->client->getQueryApi()->query('from(bucket:"dashboard") |> ...');
    });
    
  4. Error Handling Wrap operations in try-catch:

    try {
        $this->client->getWriteApi()->writePoint($point);
    } catch (InfluxDBException $e) {
        Log::error("InfluxDB write failed: " . $e->getMessage());
        // Retry or fallback logic
    }
    
  5. Async Processing Use queues for non-critical writes:

    // Dispatch a job
    LogMetricJob::dispatch($measurement, $tags, $fields);
    
    // Job class
    class LogMetricJob implements ShouldQueue {
        public function handle() {
            $this->client->getWriteApi()->writePoint($this->point);
        }
    }
    

Integration Tips

  • Laravel Events Hook into events (e.g., job.failed) to log metrics:

    event(new JobFailed($job, $exception));
    // In listener:
    $logger->log('job_failures', ['job' => $job->name, 'exception' => $exception->getMessage()]);
    
  • Middleware Log request metrics in middleware:

    public function handle($request, Closure $next) {
        $start = microtime(true);
        $response = $next($request);
        $duration = (microtime(true) - $start) * 1000;
    
        $logger->log('http_requests', [
            'tags' => ['path' => $request->path()],
            'fields' => ['duration_ms' => $duration, 'status' => $response->status()],
        ]);
    
        return $response;
    }
    
  • Artisan Commands Schedule data cleanup or maintenance:

    class PruneOldData extends Command {
        protected $signature = 'influx:prune';
        public function handle() {
            $this->client->getQueryApi()->query('delete from(bucket:"logs") where time < now() - 30d');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Token Permissions

    • Ensure the token has write permissions for the bucket/org.
    • Debug 403 errors with:
      try {
          $this->client->getWriteApi()->writePoint($point);
      } catch (InfluxDBException $e) {
          if ($e->getStatusCode() === 403) {
              Log::error("Permission denied. Check token/org/bucket.");
          }
      }
      
  2. Connection Timeouts

    • Default timeout is 5s. Increase for slow networks:
      $options = ['timeout' => 10.0];
      $client = InfluxDBClientFactory::create($url, $token, $options);
      
  3. Query Syntax

    • Use Flux (not InfluxQL) for v2+. Test queries in the InfluxDB UI first.
    • Common pitfalls:
      • Forgetting from(bucket: "...").
      • Using time() without a range filter (returns no data).
  4. Point Overhead

    • Writing millions of points without batching can overload the client. Use:
      $writeApi = $this->client->getWriteApi();
      $writeApi->setBatchSize(1000); // Points per batch
      $writeApi->setFlushInterval(5000); // ms
      
  5. Thread Safety

    • The client is not thread-safe. Avoid sharing a single instance across queues/workers. Use dependency injection.

Debugging

  1. Enable Logging Configure Monolog to log InfluxDB requests:

    $client = InfluxDBClientFactory::create($url, $token, [
        'logger' => new Monolog\Logger('influx', [new Monolog\Handler\StreamHandler(storage_path('logs/influx.log'))]),
    ]);
    
  2. Check HTTP Status Codes Catch InfluxDBException and log the status code:

    catch (InfluxDBException $e) {
        Log::error("InfluxDB Error: {$e->getStatusCode()} - {$e->getMessage()}");
    }
    
  3. Validate Points Use Point::validate() to catch malformed data:

    $point = Point::measurement('test')->floatField('value', 'invalid');
    if (!$point->validate()) {
        throw new \InvalidArgumentException("Invalid point: " . $point->getError());
    }
    

Extension Points

  1. Custom Writers Extend WriteApi for domain-specific logic:

    class CustomWriteApi extends WriteApi {
        public function writeUserEvent(string $event, array $data) {
            $point = Point::measurement('user_events')
                ->tag(['event' => $event])
                ->addFields($data);
            $this->writePoint($point);
        }
    }
    
  2. Query Builders Create a fluent query builder:

    class InfluxQueryBuilder {
        private $query = '';
    
        public function fromBucket(string $bucket): self {
            $this->query .= "from(bucket:\"{$bucket}\")";
            return $this;
        }
    
        public function range(int $hours): self {
            $this->query .= " |> range(start: -{$hours}h)";
            return $this;
        }
    
        public function build(): string {
            return $this->query;
        }
    }
    

    Usage:

    $query = (new InfluxQueryBuilder())
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity