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

influxdb/influxdb-php

PHP client library for InfluxDB 1.x: connect via host/port or DSN, write and query time-series points, and manage databases/retention policies. Community-maintained legacy v1 client; for InfluxDB 2.x use influxdb-client-php.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require influxdb/influxdb-php:^1.15.2

Ensure your composer.json includes the package under require with the new version constraint.

  1. Basic Configuration Create a config file (e.g., config/influxdb.php) with your InfluxDB connection details:

    return [
        'host' => env('INFLUXDB_HOST', 'localhost'),
        'port' => env('INFLUXDB_PORT', 8086),
        'database' => env('INFLUXDB_DATABASE', 'your_db'),
        'username' => env('INFLUXDB_USERNAME', 'root'),
        'password' => env('INFLUXDB_PASSWORD', 'root'),
        'ssl' => env('INFLUXDB_SSL', false),
        'timeout' => env('INFLUXDB_TIMEOUT', 30), // Added for clarity
    ];
    
  2. First Use Case: Writing a Point (PHP 8 Compatible)

    use InfluxDB\InfluxDB;
    use InfluxDB\Point;
    
    $client = new InfluxDB($config);
    $point = Point::measurement('measurement')
        ->tag('tag1', 'value1')
        ->addField('field1', 42)
        ->addField('field2', 'value');
    $client->writePoint($point);
    
  3. Querying Data

    $result = $client->query('SELECT * FROM "measurement"');
    foreach ($result as $row) {
        print_r($row);
    }
    

Implementation Patterns

Common Workflows

1. Structured Logging (PHP 8 Typed Properties)

Use InfluxDB to log application metrics with PHP 8 features:

$point = Point::measurement('app_logs')
    ->tag('user_id', $userId)
    ->addField('action', 'login')
    ->addField('status', 'success')
    ->timestamp(time(), 0);
$client->writePoint($point);

2. Monitoring Laravel Jobs (PHP 8 Attributes)

Track job execution with PHP 8 attributes (if using Laravel 9+):

#[HandleJobs]
public function handle()
{
    $start = microtime(true);
    try {
        // Job logic
        $duration = round(microtime(true) - $start, 2);
        $point = Point::measurement('job_metrics')
            ->tag('job_name', self::class)
            ->addField('status', 'completed')
            ->addField('duration_ms', $duration * 1000);
        $client->writePoint($point);
    } catch (\Throwable $e) { // PHP 8+ exception type
        $point = Point::measurement('job_metrics')
            ->tag('job_name', self::class)
            ->addField('status', 'failed')
            ->addField('error', $e->getMessage());
        $client->writePoint($point);
        throw $e;
    }
}

3. Batch Writes (Optimized for PHP 8)

$points = [];
for ($i = 0; $i < 100; $i++) {
    $points[] = Point::measurement('batch_test')
        ->tag('batch_id', 1)
        ->addField('value', $i)
        ->timestamp(time() + $i, 0);
}
$client->writePoints($points, InfluxDB::PRECISION_MS); // Explicit precision

4. Continuous Queries (PHP 8 Named Arguments)

$client->createContinuousQuery(
    name: 'cq_name',
    query: 'SELECT mean(value) INTO "downsampled" FROM "batch_test" GROUP BY time(1h)'
);

5. Integration with Laravel Events (PHP 8 Arrow Functions)

use Illuminate\Support\Facades\Event;

Event::listen('user.registered', fn ($user) => {
    $point = Point::measurement('user_events')
        ->tag('user_id', $user->id)
        ->addField('event', 'registered')
        ->addField('email', $user->email);
    app('influxdb')->writePoint($point);
});

Integration Tips

1. Service Provider (PHP 8 Constructor Property Promotion)

public function __construct(
    protected \Illuminate\Contracts\Config\Repository $config
) {}

public function register()
{
    $this->app->singleton('influxdb', fn () => new InfluxDB($this->config['influxdb']));
}

2. Environment-Based Config (PHP 8 Strict Types)

// .env
INFLUXDB_HOST=influx.example.com
INFLUXDB_PORT=8086
INFLuxDB_DATABASE=laravel_metrics
INFLUXDB_USERNAME=user
INFLUXDB_PASSWORD=pass
INFLUXDB_TIMEOUT=30

3. Middleware for Metrics (PHP 8 Match Expression)

public function handle($request, Closure $next)
{
    $start = microtime(true);
    $response = $next($request);
    $duration = round(microtime(true) - $start, 2);

    $status = match ($response->getStatusCode()) {
        200 => 'success',
        default => 'error',
    };

    $point = Point::measurement('http_metrics')
        ->tag('route', $request->route()->getName())
        ->addField('method', $request->method())
        ->addField('status', $status)
        ->addField('duration_ms', $duration * 1000);
    app('influxdb')->writePoint($point);

    return $response;
}

4. Scheduled Queries (PHP 8 Attributes for Commands)

#[Command(name: 'metrics:cleanup')]
public function cleanup()
{
    $client = app('influxdb');
    $client->query('DELETE FROM "batch_test" WHERE time < now() - 30d');
}

Gotchas and Tips

Pitfalls

1. PHP 8 Breaking Changes

  • Deprecated Constructors: The Point class now primarily uses the fluent builder pattern.

    // Old (deprecated)
    $point = new Point('measurement', 'tag', ['field' => 'value']);
    
    // New (recommended)
    $point = Point::measurement('measurement')
        ->tag('tag', 'value')
        ->addField('field', 'value');
    
  • Exception Handling: Use \Throwable instead of \Exception for broader compatibility.

2. SSL/TLS Improvements (PHP 8)

$client = new InfluxDB([
    'host' => 'influx.example.com',
    'ssl' => true,
    'verify_peer' => true,
    'ca_cert' => __DIR__ . '/certs/ca.pem',
    'timeout' => 30,
]);

3. Retention Policies (PHP 8 Enums)

If using InfluxDB 2.x, leverage PHP 8 enums for precision:

$client->setPrecision(InfluxDB::PRECISION_MS); // Explicit precision

4. Query Timeouts (PHP 8 Constants)

$client->setTimeout(30); // 30 seconds (use constants if available in future)

5. Tag vs. Field Confusion (PHP 8 Strict Typing)

  • Tags: Always strings (use string type hints).
  • Fields: Can be mixed types (but avoid complex objects).

Debugging

1. Enable Logging (PHP 8 Error Handling)

$client = new InfluxDB($config);
$client->setLogLevel(\InfluxDB\Logger::LOG_LEVEL_DEBUG);

try {
    $client->query('SHOW MEASUREMENTS');
} catch (\Throwable $e) {
    error_log('InfluxDB Error: ' . $e->getMessage());
}

2. Check Connection (PHP 8 Nullsafe Operator)

$config = $this->config['influxdb'] ?? [];
$client = new InfluxDB($config);

if ($client->ping()) {
    info('InfluxDB connection successful');
} else {
    error_log('InfluxDB connection failed');
}

3. Line Protocol Validation (PHP 8 String Functions)

$point = Point::measurement('test')
    ->tag('tag', 'value')
    ->addField('field', 'value
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours