PHPackages                             kundan-in/clickhouse-laravel - 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. kundan-in/clickhouse-laravel

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

kundan-in/clickhouse-laravel
============================

ClickHouse database driver for Laravel - seamlessly integrate ClickHouse into your Laravel applications

1.4.1(2mo ago)51.7k↓50.7%1[1 PRs](https://github.com/kundan-in/clickhouse-laravel/pulls)MITPHPPHP ^8.1|^8.2|^8.3|^8.4|^8.5CI failing

Since Sep 5Pushed 2mo agoCompare

[ Source](https://github.com/kundan-in/clickhouse-laravel)[ Packagist](https://packagist.org/packages/kundan-in/clickhouse-laravel)[ Docs](https://github.com/kundan-in/clickhouse-laravel)[ RSS](/packages/kundan-in-clickhouse-laravel/feed)WikiDiscussions main Synced 3d ago

READMEChangelogDependencies (12)Versions (6)Used By (0)

ClickHouse Laravel
==================

[](#clickhouse-laravel)

[![Tests](https://github.com/kundan-in/clickhouse-laravel/actions/workflows/tests.yml/badge.svg)](https://github.com/kundan-in/clickhouse-laravel/actions)[![Latest Version on Packagist](https://camo.githubusercontent.com/379d91e3d1af6a05465a72ea97231559bfb03f375fd29aa7bb65665e941add2c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b756e64616e2d696e2f636c69636b686f7573652d6c61726176656c2e737667)](https://packagist.org/packages/kundan-in/clickhouse-laravel)[![PHP Version](https://camo.githubusercontent.com/968286d7e077d8b461a1d66e07edce5ec2986ac0232b2f3f684d15987d38f982/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6b756e64616e2d696e2f636c69636b686f7573652d6c61726176656c2e737667)](https://packagist.org/packages/kundan-in/clickhouse-laravel)[![License](https://camo.githubusercontent.com/478cc7ada6f9bb93a19a13fbd335034dbc9859156096483a1c2e8b1323245cd9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6b756e64616e2d696e2f636c69636b686f7573652d6c61726176656c2e737667)](https://packagist.org/packages/kundan-in/clickhouse-laravel)

A production-ready ClickHouse database driver for Laravel with full Eloquent ORM support. Use ClickHouse the same way you use MySQL in Laravel.

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Quick Start](#quick-start)
- [Query Builder](#query-builder)
- [ClickHouse-Specific Features](#clickhouse-specific-features)
- [Schema &amp; Migrations](#schema--migrations)
- [Eloquent Model](#eloquent-model)
- [Batch Insert](#batch-insert)
- [Feature Comparison](#feature-comparison)
- [Troubleshooting](#troubleshooting)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 8.x through 13.x
- ClickHouse server (any recent version)

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

[](#installation)

```
composer require kundan-in/clickhouse-laravel
```

Publish the configuration file:

```
php artisan vendor:publish --provider="KundanIn\ClickHouseLaravel\ClickHouseServiceProvider" --tag="clickhouse-config"
```

Configuration
-------------

[](#configuration)

Add your ClickHouse connection to `config/database.php`:

```
'connections' => [
    // ... other connections

    'clickhouse' => [
        'driver'          => 'clickhouse',
        'host'            => env('CLICKHOUSE_HOST', '127.0.0.1'),
        'port'            => env('CLICKHOUSE_PORT', 8123),
        'username'        => env('CLICKHOUSE_USERNAME', 'default'),
        'password'        => env('CLICKHOUSE_PASSWORD', ''),
        'database'        => env('CLICKHOUSE_DATABASE', 'default'),
        'timeout'         => env('CLICKHOUSE_TIMEOUT', 120),
        'connect_timeout' => env('CLICKHOUSE_CONNECT_TIMEOUT', 5),
        'settings'        => [
            'readonly'           => env('CLICKHOUSE_READONLY', 0),
            'max_execution_time' => env('CLICKHOUSE_MAX_EXECUTION_TIME', 60),
        ],
    ],
],
```

### Environment Variables

[](#environment-variables)

VariableDefaultDescription`CLICKHOUSE_HOST``127.0.0.1`ClickHouse server hostname`CLICKHOUSE_PORT``8123`HTTP interface port`CLICKHOUSE_USERNAME``default`Authentication username`CLICKHOUSE_PASSWORD`*(empty)*Authentication password`CLICKHOUSE_DATABASE``default`Default database`CLICKHOUSE_TIMEOUT``120`Request timeout in seconds`CLICKHOUSE_CONNECT_TIMEOUT``5`TCP connection timeout in seconds`CLICKHOUSE_READONLY``0`Read-only mode (0=off, 1=on)`CLICKHOUSE_MAX_EXECUTION_TIME``60`Server-side query timeout in secondsQuick Start
-----------

[](#quick-start)

### Create a Model

[](#create-a-model)

```
use KundanIn\ClickHouseLaravel\Database\ClickHouseModel;

class AnalyticsEvent extends ClickHouseModel
{
    protected $connection = 'clickhouse';
    protected $table = 'analytics_events';
    public $timestamps = false;

    protected $fillable = [
        'user_id', 'event_name', 'properties', 'created_at',
    ];

    protected function casts(): array
    {
        return [
            'properties' => \KundanIn\ClickHouseLaravel\Casts\ClickHouseJson::class,
        ];
    }
}
```

### Basic Operations

[](#basic-operations)

```
// Retrieve records
$events = AnalyticsEvent::where('user_id', 123)->limit(10)->get();
$event  = AnalyticsEvent::where('event_name', 'page_view')->first();
$count  = AnalyticsEvent::count();

// Insert
AnalyticsEvent::create([
    'user_id'    => 123,
    'event_name' => 'page_view',
    'created_at' => now(),
]);

// Aggregations
$total = AnalyticsEvent::sum('duration');
$avg   = AnalyticsEvent::avg('duration');
$max   = AnalyticsEvent::max('duration');
```

Query Builder
-------------

[](#query-builder)

All standard Laravel query builder methods work:

```
use Illuminate\Support\Facades\DB;

// Where clauses
DB::connection('clickhouse')->table('events')
    ->where('status', 'active')
    ->where('score', '>', 80)
    ->whereIn('type', ['click', 'view'])
    ->whereBetween('created_at', ['2024-01-01', '2024-12-31'])
    ->whereNotNull('session_id')
    ->limit(100)
    ->get();

// Aggregations with grouping
DB::connection('clickhouse')->table('events')
    ->selectRaw('device_type, count() as total, avg(duration) as avg_duration')
    ->groupBy('device_type')
    ->having('total', '>', 100)
    ->orderByRaw('total DESC')
    ->get();

// Joins
DB::connection('clickhouse')->table('events')
    ->join('users', 'events.user_id', '=', 'users.id')
    ->select('events.*', 'users.name')
    ->get();

// Subqueries, raw expressions, pagination
DB::connection('clickhouse')->table('events')
    ->whereRaw('toDate(created_at) = today()')
    ->pluck('event_name');
```

ClickHouse-Specific Features
----------------------------

[](#clickhouse-specific-features)

### SAMPLE - Approximate Queries

[](#sample---approximate-queries)

```
// Query only 10% of the data (requires SAMPLE BY in table definition)
AnalyticsEvent::query()->sample(0.1)->count();
```

### FINAL - Deduplicated Reads

[](#final---deduplicated-reads)

```
// Force merge for ReplacingMergeTree tables
AnalyticsEvent::query()->final()->where('user_id', 123)->get();
```

### PREWHERE - I/O Optimization

[](#prewhere---io-optimization)

```
// Filter before reading full columns (reduces disk I/O)
AnalyticsEvent::query()
    ->prewhere('date', '>=', '2024-01-01')
    ->where('status', 'active')
    ->get();
```

### Array Operations

[](#array-operations)

```
// Check if array column contains a value
AnalyticsEvent::query()->whereArrayHas('tags', 'important')->get();

// Check if array has any of the given values
AnalyticsEvent::query()->whereArrayHasAny('tags', ['urgent', 'important'])->get();

// Check if array has all of the given values
AnalyticsEvent::query()->whereArrayHasAll('tags', ['reviewed', 'approved'])->get();
```

### Advanced Grouping

[](#advanced-grouping)

```
AnalyticsEvent::query()
    ->selectRaw('device_type, browser, count() as cnt')
    ->groupByWithRollup('device_type', 'browser')
    ->get();

AnalyticsEvent::query()
    ->selectRaw('device_type, browser, count() as cnt')
    ->groupByWithCube('device_type', 'browser')
    ->get();
```

### ClickHouse Aggregation Functions

[](#clickhouse-aggregation-functions)

```
// Approximate distinct count (fast)
$approxUnique = DB::connection('clickhouse')->table('events')->uniq('user_id');

// Exact distinct count
$exactUnique = DB::connection('clickhouse')->table('events')->uniqExact('user_id');
```

Schema &amp; Migrations
-----------------------

[](#schema--migrations)

### Creating Tables

[](#creating-tables)

```
use Illuminate\Support\Facades\Schema;
use KundanIn\ClickHouseLaravel\Database\ClickHouseBlueprint;

Schema::connection('clickhouse')->create('analytics_events', function (ClickHouseBlueprint $table) {
    $table->uint64('id');
    $table->string('event_name');
    $table->uint32('user_id');
    $table->float64('duration');
    $table->array('tags', 'String');
    $table->lowCardinality('device_type', 'String');
    $table->dateTime64('created_at', 3);

    $table->engine('MergeTree');
    $table->orderBy(['id', 'created_at']);
    $table->partitionBy('toYYYYMM(created_at)');
    $table->ttl('created_at + INTERVAL 90 DAY');
    $table->settings(['index_granularity' => 8192]);
});
```

### Engine Types

[](#engine-types)

```
// ReplacingMergeTree (deduplication)
$builder = Schema::connection('clickhouse')->getSchemaBuilder();
$builder->createReplacingMergeTree('events', function ($table) {
    $table->uint64('id');
    $table->uint32('version');
    $table->string('data');
    $table->orderBy('id');
}, 'version');

// SummingMergeTree (automatic aggregation)
$builder->createSummingMergeTree('daily_stats', function ($table) {
    $table->date('date');
    $table->string('page');
    $table->uint64('views');
    $table->orderBy(['date', 'page']);
}, ['views']);

// CollapsingMergeTree (row versioning)
$builder->createCollapsingMergeTree('sessions', function ($table) {
    $table->uint64('user_id');
    $table->dateTime('started_at');
    $table->int8('sign');
    $table->orderBy('user_id');
}, 'sign');
```

### Available Column Types

[](#available-column-types)

MethodClickHouse TypeDescription`int8()` / `int16()` / `int32()` / `int64()`Int8-64Signed integers`uint8()` / `uint16()` / `uint32()` / `uint64()`UInt8-64Unsigned integers`float32()` / `float64()`Float32/64Floating point`decimal($p, $s)`Decimal(P, S)Fixed-point decimal`string()`StringVariable-length string`fixedString($n)`FixedString(N)Fixed-length string`uuid()`UUIDUUID type`date()`DateCalendar date`dateTime()`DateTimeDate and time`dateTime64($precision)`DateTime64(P)High-precision datetime`boolean()`UInt8Boolean (0/1)`array($col, $type)`Array(T)Array of elements`tuple($col, $types)`Tuple(T...)Fixed-size tuple`map($col, $k, $v)`Map(K, V)Key-value map`nested($col, $struct)`Nested(...)Nested structure`enum8($col, $vals)` / `enum16()`Enum8/16Enumeration`lowCardinality($col, $type)`LowCardinality(T)Dictionary encoding`nullableColumn($col, $type)`Nullable(T)Nullable wrapper### Materialized Views

[](#materialized-views)

```
$builder = Schema::connection('clickhouse')->getSchemaBuilder();

$builder->createMaterializedView(
    'events_daily',
    'SELECT toDate(created_at) as day, count() as cnt FROM events GROUP BY day',
    'events_daily_agg'
);

$builder->dropMaterializedView('events_daily');
```

Eloquent Model
--------------

[](#eloquent-model)

### Custom Casts

[](#custom-casts)

```
use KundanIn\ClickHouseLaravel\Casts\ClickHouseArray;
use KundanIn\ClickHouseLaravel\Casts\ClickHouseJson;

class Event extends ClickHouseModel
{
    protected function casts(): array
    {
        return [
            'tags'       => ClickHouseArray::class . ':String',
            'properties' => ClickHouseJson::class,
        ];
    }
}
```

### Soft Deletes

[](#soft-deletes)

Use Laravel's `SoftDeletes` trait as normal. The driver compiles DELETE to ClickHouse's `ALTER TABLE ... DELETE` syntax:

```
use Illuminate\Database\Eloquent\SoftDeletes;

class Event extends ClickHouseModel
{
    use SoftDeletes;
}
```

### Facade

[](#facade)

```
use KundanIn\ClickHouseLaravel\Facades\ClickHouse;

$results = ClickHouse::select('SELECT count() as cnt FROM events');
$healthy = ClickHouse::healthCheck();
$version = ClickHouse::getServerVersion();
```

Batch Insert
------------

[](#batch-insert)

For high-throughput data loading, use `bulkInsert()` which uses ClickHouse's native columnar format:

```
$connection = DB::connection('clickhouse');

$rows = [
    ['user_id' => 1, 'event' => 'click', 'created_at' => '2024-01-01 00:00:00'],
    ['user_id' => 2, 'event' => 'view',  'created_at' => '2024-01-01 00:00:01'],
    // ... thousands more rows
];

$connection->bulkInsert('events', $rows);
```

This is significantly faster than individual `INSERT` statements for large datasets.

Feature Comparison
------------------

[](#feature-comparison)

FeatureMySQLClickHouse Laravel`select` / `get` / `first` / `find`YesYes`where` / `whereIn` / `whereBetween`YesYes`whereNull` / `whereNotNull`YesYes`whereDate` / `whereMonth` / `whereYear`YesYes (uses ClickHouse functions)`orderBy` / `groupBy` / `having`YesYes`limit` / `offset` / `skip` / `take`YesYes`count` / `sum` / `avg` / `min` / `max`YesYes`pluck` / `value` / `exists`YesYes`distinct` / `selectRaw` / `whereRaw`YesYes`join` / `leftJoin`YesYes`insert` / `create`YesYes`update`YesYes (ALTER TABLE UPDATE)`delete`YesYes (ALTER TABLE DELETE)`cursor` / `lazy` / `chunk`YesYes`toSql` / `toArray` / `toJson`YesYes`insertGetId`YesNo (no auto-increment)`upsert`YesNo (use ReplacingMergeTree)TransactionsYesNo (ClickHouse limitation)Foreign keysYesNo (ClickHouse limitation)`SAMPLE` / `FINAL` / `PREWHERE`NoYesArray operationsNoYes`bulkInsert`NoYes`uniq` / `uniqExact`NoYesTroubleshooting
---------------

[](#troubleshooting)

### "Too few arguments to Grammar::\_\_construct()"

[](#too-few-arguments-to-grammar__construct)

Ensure you're using v1.4.0+ which supports Laravel 12/13.

### UPDATE/DELETE require WHERE clause

[](#updatedelete-require-where-clause)

ClickHouse's ALTER TABLE UPDATE/DELETE operations require a WHERE clause for safety. This is enforced by the driver.

### "ClickHouse does not support auto-incrementing IDs"

[](#clickhouse-does-not-support-auto-incrementing-ids)

Use `UUID` columns or application-generated IDs instead of `insertGetId()`.

### Soft deletes not working

[](#soft-deletes-not-working)

Use Laravel's standard `SoftDeletes` trait. The driver handles the `ALTER TABLE ... DELETE` syntax automatically.

### Query timeout

[](#query-timeout)

Increase `CLICKHOUSE_TIMEOUT` (HTTP request timeout) and `CLICKHOUSE_MAX_EXECUTION_TIME` (server-side query limit) in your `.env`.

Testing
-------

[](#testing)

```
# Run the test suite
composer test

# Run with coverage
composer test-coverage

# Run a specific test
vendor/bin/phpunit --filter=test_name
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance83

Actively maintained with recent releases

Popularity26

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~53 days

Total

5

Last Release

88d ago

PHP version history (2 changes)1.0.0PHP ^8.1|^8.2|^8.3

1.4.1PHP ^8.1|^8.2|^8.3|^8.4|^8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/6f298eb966ed6ce0132a5b118253f9bacc37f6cbe0418fa99e54b3c28a8068a2?d=identicon)[kundancool](/maintainers/kundancool)

---

Top Contributors

[![kundancool](https://avatars.githubusercontent.com/u/198781?v=4)](https://github.com/kundancool "kundancool (7 commits)")

---

Tags

laraveldatabaseclickhouseanalyticsbig-dataolap

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kundan-in-clickhouse-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/kundan-in-clickhouse-laravel/health.svg)](https://phpackages.com/packages/kundan-in-clickhouse-laravel)
```

###  Alternatives

[glushkovds/phpclickhouse-laravel

Adapter of the most popular library https://github.com/smi2/phpClickHouse to Laravel

2051.5M2](/packages/glushkovds-phpclickhouse-laravel)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M96](/packages/mongodb-laravel-mongodb)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)[api-platform/laravel

API Platform support for Laravel

58171.6k14](/packages/api-platform-laravel)[aimeos/laravel-nestedset

Nested Set Model for Laravel

3714.4k6](/packages/aimeos-laravel-nestedset)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
