PHPackages                             nayanraval/query-pilot - 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. nayanraval/query-pilot

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

nayanraval/query-pilot
======================

AI-powered natural language search for Laravel applications — connect your database and let AI handle the queries

1.0.0(1mo ago)02↓66.7%MITPHPPHP ^8.1

Since Apr 24Pushed 1mo agoCompare

[ Source](https://github.com/NayanRaval00/laravel-querypilot-package)[ Packagist](https://packagist.org/packages/nayanraval/query-pilot)[ RSS](/packages/nayanraval-query-pilot/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

QueryPilot 🚀
============

[](#querypilot-)

AI-powered natural language search for Laravel applications. Connect your database, ask questions in plain English, and let AI handle the queries — no SQL required.

[![Latest Version](https://camo.githubusercontent.com/a4ad77c4ab014d763ab16d70c609a9de58f59e7f31d6018eacb8989762950893/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6179616e726176616c2f71756572792d70696c6f742e737667)](https://packagist.org/packages/nayanraval/query-pilot)[![Total Downloads](https://camo.githubusercontent.com/5334ef97a8c8378861b312d4f57db21b7830e6ba49e35c7ad1d86b892400c053/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e6179616e726176616c2f71756572792d70696c6f742e737667)](https://packagist.org/packages/nayanraval/query-pilot)[![License](https://camo.githubusercontent.com/cdcf30a256590fadccb9e965a5be56773c656e33b3085029b10f6f7f785e537d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e6179616e726176616c2f71756572792d70696c6f742e737667)](https://packagist.org/packages/nayanraval/query-pilot)

---

Features
--------

[](#features)

- 🤖 **Natural language to database** — ask questions in plain English, get instant results
- 🔗 **Auto-detects Eloquent relationships** — automatically builds JOIN queries from your models
- 🖼️ **Image URL resolution** — automatically generates public URLs for image columns
- ⚡ **Query caching &amp; performance tracking** — built-in cache with execution time monitoring
- 🛡️ **SQL injection protection** — validates all queries before execution
- 🎯 **Multi-provider support** — works with Gemini, OpenAI, Anthropic, and more via Laravel AI SDK

---

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

[](#requirements)

- PHP 8.1+
- Laravel 11.0+ or 12.0+
- `laravel/ai` package (installed automatically)

---

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

[](#installation)

### Step 1: Install the package

[](#step-1-install-the-package)

```
composer require nayanraval/query-pilot
```

### Step 2: Publish the configuration file

[](#step-2-publish-the-configuration-file)

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

This creates `config/querypilot.php` in your application.

### Step 3: Configure your AI provider

[](#step-3-configure-your-ai-provider)

Add to your `.env` file:

```
# AI Provider (gemini, openai, anthropic, etc.)
QUERYPILOT_PROVIDER=gemini

# API Key for your chosen provider
GEMINI_API_KEY=your_gemini_api_key_here

# Optional: Customize limits
QUERYPILOT_MAX_ROWS=100
QUERYPILOT_CACHE_TTL=60
```

> **💡 Tip:** You can use any provider supported by the [Laravel AI SDK](https://laravel.com/docs/ai-sdk). Configure additional providers in `config/ai.php`.

### Step 4: Configure your database tables

[](#step-4-configure-your-database-tables)

Edit `config/querypilot.php` and add the tables you want to expose to AI:

```
'tables' => [
    'users' => [
        'label'      => 'Registered users',
        'model'      => \App\Models\User::class,
        'searchable' => ['id', 'name', 'email', 'created_at'],
        'image'      => 'avatar',        // column that holds image path
        'image_disk' => 'public',        // Laravel storage disk
    ],
    'products' => [
        'label'      => 'Products catalog',
        'model'      => \App\Models\Product::class,
        'searchable' => ['id', 'name', 'sku', 'price', 'stock', 'user_id'],
        'image'      => 'image',
        'image_disk' => 'public',
    ],
],
```

### Step 5: Ensure your Eloquent models have relationships defined

[](#step-5-ensure-your-eloquent-models-have-relationships-defined)

QueryPilot automatically reads your Eloquent relationships to build JOIN queries:

```
// app/Models/User.php
public function products()
{
    return $this->hasMany(Product::class);
}

public function profile()
{
    return $this->hasOne(Profile::class);
}
```

---

Usage
-----

[](#usage)

### Full API Response Example

[](#full-api-response-example)

```
use QueryPilot\QueryPilotAgent;

Route::get('/api/query', function () {
    try {
        $start = microtime(true);
        $agent = app(QueryPilotAgent::class);

        $response = $agent->prompt(
            request('q', 'Give me the first user with their profile'),
            provider: config('querypilot.provider')
        );

        return response()->json([
            'success'       => true,
            'answer'        => $response['answer'] ?? '',
            'table'         => $response['table'] ?? '',
            'count'         => $response['count'] ?? 0,
            'rows'          => $response['rows'] ?? [],
            'total_time_ms' => round((microtime(true) - $start) * 1000),
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error'   => $e->getMessage(),
        ], 500);
    }
});
```

### Example Queries

[](#example-queries)

```
// Simple queries
"Show me all users"
"Give me products under $50"
"Find users who registered today"

// Queries with relationships
"Show me John with his profile and products"
"Get users with their latest posts"
"Find products and their owner details"

// Filtered queries
"Show me active products with stock greater than 10"
"Get users whose email contains gmail"
"Find the 5 most recent posts"
```

---

Response Structure
------------------

[](#response-structure)

```
{
    "success": true,
    "answer": "Here are the 3 users who signed up this month: John Doe, Jane Smith, and Bob Wilson.",
    "table": "users",
    "count": 3,
    "rows": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com",
            "avatar": "avatars/john.jpg",
            "avatar_url": "http://localhost/storage/avatars/john.jpg",
            "created_at": "2026-04-15 10:30:00"
        }
    ],
    "total_time_ms": 1243
}
```

---

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

[](#configuration)

### Available Providers

[](#available-providers)

QueryPilot supports all providers from the Laravel AI SDK:

- **Gemini** (Google) — `provider: 'gemini'`
- **OpenAI** (GPT-4, GPT-4o) — `provider: 'openai'`
- **Anthropic** (Claude) — `provider: 'anthropic'`
- **Groq** — `provider: 'groq'`
- **Local models** via Ollama

Configure your preferred provider in `config/ai.php`:

```
// config/ai.php
'default' => env('AI_PROVIDER', 'gemini'),

'providers' => [
    'gemini' => [
        'driver' => 'gemini',
        'key'    => env('GEMINI_API_KEY'),
        'model'  => env('GEMINI_MODEL', 'gemini-2.0-flash'),
    ],
    'openai' => [
        'driver' => 'openai',
        'key'    => env('OPENAI_API_KEY'),
        'model'  => env('OPENAI_MODEL', 'gpt-4o'),
    ],
],
```

### Cache Configuration

[](#cache-configuration)

```
QUERYPILOT_CACHE_TTL=60  # Cache results for 60 seconds
```

Set to `0` to disable caching.

### Query Limits

[](#query-limits)

```
QUERYPILOT_MAX_ROWS=100  # Maximum rows returned per query
```

---

Security
--------

[](#security)

QueryPilot includes built-in protection against SQL injection:

- ✅ Only `SELECT` queries are allowed
- ✅ Blocks dangerous keywords (`DROP`, `DELETE`, `UPDATE`, `INSERT`, etc.)
- ✅ Only whitelisted tables and columns can be queried
- ✅ Validates all JOIN clauses against configured models
- ✅ Sanitizes user input before query execution

**Important:** Only expose tables you want users to search. Never add sensitive tables like `password_resets`, `sessions`, or admin-only tables to the config.

---

Troubleshooting
---------------

[](#troubleshooting)

### "Table X is not allowed"

[](#table-x-is-not-allowed)

Add the table to `config/querypilot.php` under the `tables` array.

### "Column Y is not allowed"

[](#column-y-is-not-allowed)

Add the column to the `searchable` array for that table.

### AI returns "No data found" for existing records

[](#ai-returns-no-data-found-for-existing-records)

Check that:

1. Your Eloquent models have relationships defined
2. The `model` key in config points to the correct model class
3. Foreign key columns are included in the `searchable` array

### Image URLs not resolving

[](#image-urls-not-resolving)

Ensure:

1. `image` column name matches exactly
2. `image_disk` is set correctly (usually `'public'`)
3. Storage is linked: `php artisan storage:link`

---

Testing
-------

[](#testing)

```
# Run package tests
php artisan test tests/Feature/QueryPilotTest.php
```

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history.

---

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

[](#contributing)

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

---

License
-------

[](#license)

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

---

Credits
-------

[](#credits)

**Author:** Nayan Raval
**Email:**
**GitHub:** [github.com/NayanRaval00](https://github.com/NayanRaval00)

Built with ❤️ using the [Laravel AI SDK](https://laravel.com/docs/ai-sdk)

---

Support
-------

[](#support)

- 📧 Email:

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance91

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

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

Unknown

Total

1

Last Release

46d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3524417?v=4)[nayanraval](/maintainers/nayanraval)[@NayanRaval](https://github.com/NayanRaval)

---

Top Contributors

[![NayanRaval00](https://avatars.githubusercontent.com/u/50438576?v=4)](https://github.com/NayanRaval00 "NayanRaval00 (11 commits)")

---

Tags

searchlaraveldatabaseaieloquentqueryopenaiGemininatural-language

### Embed Badge

![Health badge](/badges/nayanraval-query-pilot/health.svg)

```
[![Health](https://phpackages.com/badges/nayanraval-query-pilot/health.svg)](https://phpackages.com/packages/nayanraval-query-pilot)
```

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k5.0M31](/packages/tucker-eric-eloquentfilter)[sarfraznawaz2005/indexer

Laravel package to monitor SELECT queries and offer best possible INDEX fields.

562.7k](/packages/sarfraznawaz2005-indexer)

PHPackages © 2026

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