PHPackages                             mostafaarafat/laravel-ai-database - 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. mostafaarafat/laravel-ai-database

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

mostafaarafat/laravel-ai-database
=================================

AI-powered database query assistant for Laravel

v1.0.0(4mo ago)471MITPHPPHP ^8.0|^8.1|^8.2|^8.3|^8.4|^8.5

Since Feb 18Pushed 4mo agoCompare

[ Source](https://github.com/mostafaarafatt/laravel-ai-database)[ Packagist](https://packagist.org/packages/mostafaarafat/laravel-ai-database)[ RSS](/packages/mostafaarafat-laravel-ai-database/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (3)Versions (2)Used By (1)

Laravel AI Database Assistant
=============================

[](#laravel-ai-database-assistant)

[![Latest Version on Packagist](https://camo.githubusercontent.com/5209fc5c43289351b8f3e358e827031a339abd56a5af6838ecd40bab549dd87b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6f73746166616172616661742f6c61726176656c2d61692d64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mostafaarafat/laravel-ai-database)[![Total Downloads](https://camo.githubusercontent.com/37bfea4a382d92d2f77664ec3447ad3ff97495ae07408f2204c1d2e4c82cd51d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6f73746166616172616661742f6c61726176656c2d61692d64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mostafaarafat/laravel-ai-database)[![License](https://camo.githubusercontent.com/19666c9545c4548fc910cf0ff8d0de7a3183908eee7993da7a2034934ea859ca/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d6f73746166616172616661742f6c61726176656c2d61692d64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mostafaarafat/laravel-ai-database)

Transform natural language questions into SQL queries and get human-readable answers using AI. This Laravel package integrates multiple AI providers (Anthropic Claude, OpenAI, Google Gemini) to make database querying accessible to everyone.

✨ Features
----------

[](#-features)

- 🤖 **Multiple AI Providers**: Support for Anthropic Claude, OpenAI GPT, and Google Gemini
- 🔒 **Security First**: Built-in strict mode prevents write operations
- ⚡ **Smart Schema Detection**: Automatically identifies relevant tables for queries
- 💾 **Schema Caching**: Reduces API calls and improves performance
- 🎯 **Multiple Interfaces**: Use via Facade, DB helper, or Artisan commands
- 🗃️ **Multi-Database Support**: Works with MySQL, PostgreSQL, and SQLite
- 📊 **Flexible Responses**: Get SQL queries, human answers, or detailed results

📋 Requirements
--------------

[](#-requirements)

- PHP 8.0 or higher
- Laravel 8.x, 9.x, 10.x, or 11.x (via illuminate/support)
- One of the following AI provider API keys:
    - Anthropic API key (recommended)
    - OpenAI API key
    - Google Gemini API key

📦 Installation
--------------

[](#-installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require mostafaarafat/laravel-ai-database
```

### Step 2: Publish Configuration

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

```
php artisan vendor:publish --tag=ai-database-config
```

This creates `config/ai-database.php` in your Laravel application.

### Step 3: Configure Environment Variables

[](#step-3-configure-environment-variables)

Add your AI provider credentials to `.env`:

```
# Choose your AI provider (anthropic, openai, or gemini)
AI_DATABASE_PROVIDER=anthropic

# Anthropic Configuration
ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxxx
ANTHROPIC_MODEL=claude-sonnet-4-20250514

# OpenAI Configuration (alternative)
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxx
OPENAI_MODEL=gpt-4o-mini

# Google Gemini Configuration (alternative)
GEMINI_API_KEY=xxxxxxxxxxxxxxxxxxxxx
GEMINI_MODEL=gemini-1.5-pro

# Database Configuration
AI_DATABASE_CONNECTION=mysql
AI_DATABASE_STRICT_MODE=true
AI_DATABASE_MAX_TABLES=15

# Cache Configuration
AI_DATABASE_CACHE_ENABLED=true
AI_DATABASE_CACHE_TTL=3600
```

🚀 Quick Start
-------------

[](#-quick-start)

### Basic Usage

[](#basic-usage)

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

// Get a human-readable answer
$answer = DB::ask('How many users are registered?');
// Output: "There are 1,234 users registered in the database."

// Get just the SQL query
$sql = DB::askForQuery('Show me users created this month');
// Output: "SELECT * FROM users WHERE created_at >= '2025-02-01'"

// Get detailed response with all information
$result = DB::askDetailed('What is the total revenue?');
// Output: [
//     'question' => 'What is the total revenue?',
//     'sql' => 'SELECT SUM(amount) as total FROM orders',
//     'results' => [['total' => 50000]],
//     'answer' => 'The total revenue is $50,000.',
//     'rows' => 1
// ]
```

### Using Artisan Commands

[](#using-artisan-commands)

```
# Get a natural language answer
php artisan db:ask "How many active users do we have?"

# Show detailed information including SQL and raw results
php artisan db:ask "Show me top 5 products" -v

# Get only the SQL query
php artisan db:ask "List all pending orders" --sql-only

# Use a specific database connection
php artisan db:ask "How many records?" --connection=secondary
```

📚 Detailed Usage
----------------

[](#-detailed-usage)

### 1. Getting Human-Readable Answers

[](#1-getting-human-readable-answers)

The `ask()` method generates SQL, executes it, and returns a natural language answer:

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

// Simple questions
$answer = DB::ask('How many users are there?');

// Complex aggregations
$answer = DB::ask('What is the average order value for the last 30 days?');

// Filtering and sorting
$answer = DB::ask('Show me the top 5 customers by total spending');

// Joins and relationships
$answer = DB::ask('Which products have never been ordered?');
```

### 2. Getting SQL Queries Only

[](#2-getting-sql-queries-only)

Use `askForQuery()` when you want the SQL without executing it:

```
// Get the SQL query
$sql = DB::askForQuery('Find users who signed up today');

// You can then modify or log it
Log::info('Generated SQL:', ['sql' => $sql]);

// Execute it yourself if needed
$results = DB::select($sql);
```

### 3. Getting Detailed Results

[](#3-getting-detailed-results)

Use `askDetailed()` for complete information:

```
$result = DB::askDetailed('Show me recent orders');

// Access all parts of the response
echo $result['question'];  // The original question
echo $result['sql'];       // The generated SQL
print_r($result['results']); // Raw database results
echo $result['answer'];    // Human-readable answer
echo $result['rows'];      // Number of rows returned
```

### 4. Using Specific Database Connections

[](#4-using-specific-database-connections)

```
// Use a specific connection
$answer = DB::ask('How many records?', 'secondary');

$sql = DB::askForQuery('List all items', 'analytics');

$result = DB::askDetailed('Show statistics', 'reporting');
```

### 5. Using in Controllers

[](#5-using-in-controllers)

```
