PHPackages                             deflinhec/laravel-clickhouse - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. deflinhec/laravel-clickhouse

ActiveLibrary[Database &amp; ORM](/categories/database)

deflinhec/laravel-clickhouse
============================

Laravel ClickHouse integration package

2.1.1(6mo ago)12.0k↓100%MITPHPPHP ^7.1.3

Since Jul 14Pushed 6mo agoCompare

[ Source](https://github.com/deflinhec/laravel-clickhouse)[ Packagist](https://packagist.org/packages/deflinhec/laravel-clickhouse)[ RSS](/packages/deflinhec-laravel-clickhouse/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (11)Used By (0)

Laravel ClickHouse Package
==========================

[](#laravel-clickhouse-package)

[![Latest Stable Version](https://camo.githubusercontent.com/939cee69bfb3b67f3a6baa9f6a8fe666cd4521c792506b329e0fd153c4655d82/68747470733a2f2f706f7365722e707567782e6f72672f6465666c696e6865632f6c61726176656c2d636c69636b686f7573652f762f737461626c65)](https://packagist.org/packages/deflinhec/laravel-clickhouse)[![License](https://camo.githubusercontent.com/a442ed42955a387996bfa4cb327c6a3615d7e0b6ba34b26caa1289cc9338e72c/68747470733a2f2f706f7365722e707567782e6f72672f6465666c696e6865632f6c61726176656c2d636c69636b686f7573652f6c6963656e7365)](https://packagist.org/packages/deflinhec/laravel-clickhouse)[![composer.lock](https://camo.githubusercontent.com/946bc0d9463672702f8eaf5ac2ae17716229c45322266b87ad3155d96b505a81/68747470733a2f2f706f7365722e707567782e6f72672f6465666c696e6865632f6c61726176656c2d636c69636b686f7573652f636f6d706f7365726c6f636b)](https://packagist.org/packages/deflinhec/laravel-clickhouse)

Laravel ClickHouse integration package based on `smi2/phpclickhouse` client with advanced features including migration system, cluster support, and comprehensive exception handling.

- **Vendor**: deflinhec
- **Package**: laravel-clickhouse
- **[Composer](https://getcomposer.org/):** `composer require deflinhec/laravel-clickhouse`

Features
--------

[](#features)

- 🔗 ClickHouse connection management with multiple connection support
- 🚀 Migration system with Laravel integration
- 📊 Query builder and custom query execution
- 🧪 Testing tools and CLI interface
- 📝 Complete logging and monitoring
- ⚡ High-performance query support
- 🌐 Cluster mode with load balancing (round-robin, random, failover)
- 🛡️ Comprehensive exception handling with custom error types
- 🔧 Artisan commands for management and testing
- 📦 Composer package with proper autoloading

PHP Compatibility
-----------------

[](#php-compatibility)

This package is compatible with:

- **PHP 7.3+** (with full type hint support)
- **Laravel 5.0+** through **Laravel 12.0+**

Installation
------------

[](#installation)

### 1. Install Package

[](#1-install-package)

```
composer require deflinhec/laravel-clickhouse
```

### 2. Publish Configuration Files

[](#2-publish-configuration-files)

```
php artisan vendor:publish --tag=clickhouse-config
```

### 3. Set Environment Variables

[](#3-set-environment-variables)

Add the following to your `.env` file:

```
# ClickHouse Connection Settings
CLICKHOUSE_HOST=localhost
CLICKHOUSE_PORT=8123
CLICKHOUSE_USERNAME=default
CLICKHOUSE_PASSWORD=clickhouse
CLICKHOUSE_DATABASE=default
CLICKHOUSE_SSL=false
CLICKHOUSE_READONLY=true
CLICKHOUSE_TIMEOUT=30

# Logging Settings
CLICKHOUSE_LOGGING_ENABLED=true
CLICKHOUSE_LOGGING_CHANNEL=clickhouse

# Migration Settings
CLICKHOUSE_MIGRATIONS_PATH=database/migrations/clickhouse

# Cluster Mode Settings (Optional)
CLICKHOUSE_CONNECTION=cluster
CLICKHOUSE_CLUSTER_MODE=round_robin
CLICKHOUSE_CLUSTER_NODES=node1,node2
CLICKHOUSE_CLUSTER_PORTS=8123,8123
CLICKHOUSE_CLUSTER_WEIGHTS=1,1
CLICKHOUSE_CLUSTER_RETRY_ATTEMPTS=3
CLICKHOUSE_CLUSTER_RETRY_DELAY=1000
CLICKHOUSE_CLUSTER_HEALTH_CHECK_INTERVAL=30
CLICKHOUSE_CLUSTER_FAILOVER_TIMEOUT=5000
```

Basic Usage
-----------

[](#basic-usage)

### Service-based Approach

[](#service-based-approach)

```
use Deflinhec\LaravelClickHouse\Services\Service;

$clickHouse = new Service();

// Execute custom query
$result = $clickHouse->executeQuery('SELECT * FROM your_table LIMIT 10');

// Test connection
if ($clickHouse->testConnection()) {
    echo "Connection successful!";
}
```

Exception Handling
------------------

[](#exception-handling)

The package provides a custom `ClickHouseException` class with comprehensive error types:

```
use Deflinhec\LaravelClickHouse\Exceptions\ClickHouseException;

try {
    $result = $clickHouse->executeQuery('SELECT * FROM non_existent_table');
} catch (ClickHouseException $e) {
    echo "Error Type: " . $e->getErrorType();
    echo "Error Code: " . $e->getErrorCode();
    echo "Error Message: " . $e->getMessage();
    echo "Error Context: " . json_encode($e->getContext());
}

// Available error types
ClickHouseException::connectionError($message, $context);
ClickHouseException::queryError($message, $context);
ClickHouseException::configurationError($message, $context);
ClickHouseException::migrationError($message, $context);
ClickHouseException::clusterError($message, $context);
ClickHouseException::authenticationError($message, $context);
ClickHouseException::permissionError($message, $context);
ClickHouseException::timeoutError($message, $context);
ClickHouseException::syntaxError($message, $context);
ClickHouseException::resourceError($message, $context);
```

Artisan Commands
----------------

[](#artisan-commands)

### Interactive CLI

[](#interactive-cli)

```
# Open ClickHouse interactive CLI
php artisan clickhouse
```

### Connection Testing

[](#connection-testing)

```
# Open interactive CLI (includes connection test)
php artisan clickhouse

# Execute single query
php artisan clickhouse --query="SELECT COUNT(*) FROM your_table"

# Specify connection
php artisan clickhouse --connection=local
```

### Cluster Management

[](#cluster-management)

```
# Check cluster status
php artisan clickhouse:cluster:status

# Detailed cluster status
php artisan clickhouse:cluster:status --detailed

# Check cluster status with specific connection
php artisan clickhouse:cluster:status --connection=cluster
```

### Migration Management

[](#migration-management)

```
# Create migration file
php artisan make:clickhouse-migration create_users_table
php artisan make:clickhouse-migration create_orders_table --table=orders
php artisan make:clickhouse-migration create_products_table --create --columns="name:string,price:decimal,is_active:bool"

# Run migrations
php artisan clickhouse:migrate

# Preview migration SQL
php artisan clickhouse:migrate --pretend

# Specify migration path
php artisan clickhouse:migrate --path=database/migrations/clickhouse

# Rollback migrations
php artisan clickhouse:migrate:rollback

# Rollback specific number of migrations
php artisan clickhouse:migrate:rollback --step=3
```

Migration System
----------------

[](#migration-system)

### Important Notes

[](#important-notes)

ClickHouse migrations use Laravel's default `migrations` table to track migration status, rather than creating additional tables in ClickHouse. This ensures migration records are consistent with other Laravel migrations.

### Creating Migration Files

[](#creating-migration-files)

Use the `make:clickhouse-migration` command to quickly create migration files:

```
# Basic usage
php artisan make:clickhouse-migration create_users_table

# Specify table name
php artisan make:clickhouse-migration create_orders_table --table=orders

# Create table (explicitly specified)
php artisan make:clickhouse-migration create_products_table --create

# Custom fields
php artisan make:clickhouse-migration create_analytics_table --columns="user_id:int,name:string,score:float,is_active:bool,tags:array"

# Specify path
php artisan make:clickhouse-migration create_test_table --path=database/migrations/custom
```

### Supported Field Types

[](#supported-field-types)

The command supports the following field type mappings:

- `string` → `String`
- `int` / `integer` → `Int32`
- `bigint` → `Int64`
- `float` → `Float32`
- `double` → `Float64`
- `decimal` → `Decimal(10,2)`
- `bool` / `boolean` → `UInt8`
- `date` → `Date`
- `datetime` / `timestamp` → `DateTime`
- `array` → `Array(String)`
- `json` → `String`

### Manual Migration File Creation

[](#manual-migration-file-creation)

```
