PHPackages                             moirei/hogql - 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. [API Development](/categories/api)
4. /
5. moirei/hogql

ActiveLibrary[API Development](/categories/api)

moirei/hogql
============

Interact with PostHog's HogQL API using Laravel's query builder.

0.3.0(3mo ago)21721MITPHPPHP ^8.2

Since Jul 29Pushed 3mo agoCompare

[ Source](https://github.com/moirei/hogql)[ Packagist](https://packagist.org/packages/moirei/hogql)[ RSS](/packages/moirei-hogql/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (9)Versions (7)Used By (0)

moirei/hogql
============

[](#moireihogql)

This PostHog (HogQL) Laravel Query Builder package enables you to interact with PostHog's HogQL API using Laravel's query builder. This package simplifies the process of building and executing analytical queries, allowing you to leverage Laravel's intuitive query syntax while working with PostHog's powerful data analytics platform.

Features
--------

[](#features)

- **Familiar Syntax**: Use Laravel's query builder syntax to construct complex queries.
- **Secure Access**: Validate and restrict access to specific tables within PostHog.
- **Seamless Integration**: Execute queries and retrieve results directly from PostHog.
- **Configurable Aliases**: Easily map and alias table and column names for better readability.
- **Eloquent Metrics**: Easily integrate and use with [moirei/eloquent-metrics](https://github.com/moirei/eloquent-metrics).

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

[](#installation)

```
composer require moirei/hogql
```

Publish the config (optional).

```
php artisan vendor:publish --tag="hogql-config"
```

Setup
-----

[](#setup)

After installation, you'll need to obtain your [Product ID](https://us.posthog.com/project/22657/settings/project-details#variables) and a [personal API key](https://posthog.com/docs/api#private-endpoint-authentication). This key will need atleast `query:read` scope.

Update your `.env` file with `POSTHOG_PRODUCT_ID` and `POSTHOG_API_TOKEN` accordingly.

Usage
-----

[](#usage)

```
use MOIREI\HogQl\Facade as HogQl;
...

HogQl::select(['event_name', 'COUNT(*) as event_count'])
                ->whereBetween('timestamp', ['2024-01-01 12:00:00', '2024-07-28 10:15:39'])
                ->groupBy('event_name')
                ->orderBy('event_count', 'DESC')
                ->get();
```

> Note: the `get()` operation always transforms the raw result. E.g. the query above returns a collection of arrays with `event_name` and `event_count` keys/values.

### Extended usage

[](#extended-usage)

**Get a DB Query Builder instance**:

```
$query = HogQl::query();
// OR
$query = HogQl::query('some_other_table');

$result = $query->get();
```

**Start a query with select statement**:

```
$query = HogQl::select('properties.$os as os')->where('os', 'iOS');
$result = $query->count();
```

**Referencing aliases**:

Setup aliases in config:

```
// config/hogql.php
...
    'aliases' => [
        'device' => 'properties.$device',
        'os' => 'properties.$os',
        ...
    ],
```

Reference them via selects:

```
$query = HogQl::select(['device', 'os']);
$result = $query->get();
```

**Get an Eloquent Query Builder instance**:

Returns eloquent model instances.

```
$query = HogQl::model();
// OR
$query = HogQl::eloquent();

$result = $query->select(['properties.$current_url', 'properties.$device'])->get();
```

**Parse a query string**:

```
$query = HogQl::parse('SELECT event FROM events');
$result = $query->where('properties.my_user', $user->id)->count();
```

**Get the results of a string query**:

```
$response = HogQl::get('SELECT event, COUNT() FROM events GROUP BY event ORDER BY COUNT() DESC');
```

**Get the raw results of a string query**:

Returns the raw original [HogQLQueryResponse](https://posthog.com/docs/hogql#query-api) response.

```
$response = HogQl::getRaw('SELECT event, COUNT() FROM events GROUP BY event ORDER BY COUNT() DESC');
```

**With moirei/eloquent-metrics**:

> moirei/eloquent-metrics is Chartjs compatible.

```
$query = HogQl::eloquent()->where('event', '$pageview');

$metrics = Trend::make()
            ->name('Page views')
            ->period('week')
            ->sumByDays($query);
```

Tests
-----

[](#tests)

```
composer test
```

Contribution Guidelines
-----------------------

[](#contribution-guidelines)

Any pull requests or discussions are welcome. Note that every pull request providing new feature or correcting a bug should be created with appropriate unit tests.

License
-------

[](#license)

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

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance80

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

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 ~120 days

Recently: every ~150 days

Total

6

Last Release

104d ago

PHP version history (2 changes)0.1.0PHP ^7.4|^8.0

0.3.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/7ac6a15a7b2f9055a98e4419e0d2820f72db3567706837ec388baee535d3e3e7?d=identicon)[moirei](/maintainers/moirei)

---

Top Contributors

[![augustusnaz](https://avatars.githubusercontent.com/u/51074349?v=4)](https://github.com/augustusnaz "augustusnaz (6 commits)")

---

Tags

laravelqueryposthogmoireihogql

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/moirei-hogql/health.svg)

```
[![Health](https://phpackages.com/badges/moirei-hogql/health.svg)](https://phpackages.com/packages/moirei-hogql)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M194](/packages/laravel-ai)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45444.2k1](/packages/pressbooks-pressbooks)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)[illuminate/queue

The Illuminate Queue package.

21332.6M1.6k](/packages/illuminate-queue)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5021.9k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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