PHPackages                             nalrep/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. nalrep/laravel

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

nalrep/laravel
==============

AI-powered, schema-aware, dynamic report generation for Laravel

v0.1(6mo ago)01MITPHPPHP ^8.2

Since Nov 19Pushed 5mo agoCompare

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

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

Nalrep: Natural Language Reporting for Laravel
==============================================

[](#nalrep-natural-language-reporting-for-laravel)

[![Latest Stable Version](https://camo.githubusercontent.com/35d11d491d34fde39d3bb2173aa3cdd22e0a2522ef72ad706ac6978a7f6c9be8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e616c7265702f6c61726176656c2e7376673f7374796c653d666c617426636f6c6f723d344341463530)](https://packagist.org/packages/nalrep/laravel)[![Total Downloads](https://camo.githubusercontent.com/27dbe2eed982fb2f98a1e5132b6cf8149310d668db095de38ee02e818ae5844f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e616c7265702f6c61726176656c2e7376673f7374796c653d666c617426636f6c6f723d323139364633)](https://packagist.org/packages/nalrep/laravel)[![License](https://camo.githubusercontent.com/8687d1fb4ed16589bdc0a8915ece676a4b2667d674e88330cab460cad40987ca/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e616c7265702f6c61726176656c2e7376673f7374796c653d666c617426636f6c6f723d373935353438)](LICENSE)

**Nalrep** (Natural Language Reporting) is a powerful Laravel package that empowers your application with AI-driven reporting capabilities. It allows users to generate complex database reports using simple natural language prompts, converting them into safe, executable Laravel Query Builder code.

---

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

[](#-table-of-contents)

- [Example Report](#-example-report)
- [Features](#-features)
- [How It Works Internally](#-how-it-works-internally)
- [Installation](#-installation)
- [Configuration](#%EF%B8%8F-configuration)
    - [AI Provider](#1-ai-provider)
    - [Request Timeout](#2-request-timeout)
    - [Schema Exclusion](#3-schema-exclusion)
    - [Model Scanning](#4-model-scanning)
    - [Common Classes (Auto-Imports)](#5-common-classes-auto-imports)
    - [Frontend Component Settings](#6-frontend-component-settings)
    - [Safety Settings](#8-safety-settings)
- [Security Architecture](#-security-architecture)
- [Usage](#-usage)
    - [Blade Component](#blade-component)
    - [Customizing the View](#customizing-the-view)
    - [Programmatic Usage](#programmatic-usage)
- [Error Handling](#%EF%B8%8F-error-handling)
    - [Exception Types](#exception-types)
    - [Handling Errors in Your Code](#handling-errors-in-your-code)
    - [How Errors Are Surfaced](#how-errors-are-surfaced)
    - [AI Error Detection](#ai-error-detection)
- [Extensibility](#-extensibility)
    - [Custom AI Agents](#custom-ai-agents)
    - [Using PromptBuilder Standalone](#using-promptbuilder-standalone)
- [License](#-license)

---

📊 Example Report
----------------

[](#-example-report)

[![Sample Report](https://private-user-images.githubusercontent.com/43961320/517116175-f3dc22b8-173d-47dd-8219-440e3827680a.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzU0MzQwMTksIm5iZiI6MTc3NTQzMzcxOSwicGF0aCI6Ii80Mzk2MTMyMC81MTcxMTYxNzUtZjNkYzIyYjgtMTczZC00N2RkLTgyMTktNDQwZTM4Mjc2ODBhLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjA0MDYlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwNDA2VDAwMDE1OVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTZlYjBlOTRhZGNlNTBhMjBkN2JjNjFkYWVlYjg2YjYxMzA5NzU2OTNhODE0OTEwYzk0YmU1ZmU4ZTgyYTQyYWYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.RmkahPF4zFiha2ZizsKQW5JcojDSE35SVEOU3U5pJ0c)](https://private-user-images.githubusercontent.com/43961320/517116175-f3dc22b8-173d-47dd-8219-440e3827680a.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzU0MzQwMTksIm5iZiI6MTc3NTQzMzcxOSwicGF0aCI6Ii80Mzk2MTMyMC81MTcxMTYxNzUtZjNkYzIyYjgtMTczZC00N2RkLTgyMTktNDQwZTM4Mjc2ODBhLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjA0MDYlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwNDA2VDAwMDE1OVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTZlYjBlOTRhZGNlNTBhMjBkN2JjNjFkYWVlYjg2YjYxMzA5NzU2OTNhODE0OTEwYzk0YmU1ZmU4ZTgyYTQyYWYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.RmkahPF4zFiha2ZizsKQW5JcojDSE35SVEOU3U5pJ0c)

*Generate beautiful reports from natural language queries like "Top 5 customers by total purchase revenue"*

[![JSON Report](https://private-user-images.githubusercontent.com/43961320/517152085-dd9fa530-5bc2-4d90-a687-e97af0067c67.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzU0MzQwMTksIm5iZiI6MTc3NTQzMzcxOSwicGF0aCI6Ii80Mzk2MTMyMC81MTcxNTIwODUtZGQ5ZmE1MzAtNWJjMi00ZDkwLWE2ODctZTk3YWYwMDY3YzY3LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjA0MDYlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwNDA2VDAwMDE1OVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTQyNTA0YzkyOGRmZjdkMjcwZDU0ZGY2N2Q3NWIzNDMzZjQwZGRhMTliMjZkNzBjYTNjNTJjNmU2NDg3ZTRmMTUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.azcgT3pcOyNaEdLC0w3hXhEunT2kOiwIxVUeeprWbrc)](https://private-user-images.githubusercontent.com/43961320/517152085-dd9fa530-5bc2-4d90-a687-e97af0067c67.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzU0MzQwMTksIm5iZiI6MTc3NTQzMzcxOSwicGF0aCI6Ii80Mzk2MTMyMC81MTcxNTIwODUtZGQ5ZmE1MzAtNWJjMi00ZDkwLWE2ODctZTk3YWYwMDY3YzY3LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjA0MDYlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwNDA2VDAwMDE1OVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTQyNTA0YzkyOGRmZjdkMjcwZDU0ZGY2N2Q3NWIzNDMzZjQwZGRhMTliMjZkNzBjYTNjNTJjNmU2NDg3ZTRmMTUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.azcgT3pcOyNaEdLC0w3hXhEunT2kOiwIxVUeeprWbrc)

*Get clean JSON responses for API integrations: "give me list of all users with count of customers served and sales made"*

---

🚀 Features
----------

[](#-features)

- **Natural Language to SQL**: Convert questions like "Show me top selling products last month" into database queries.
- **Safe Execution**: Built-in validation ensures only read-only queries are executed.
- **Context-Aware**: Automatically scans your database schema and Eloquent models to provide the AI with accurate context.
- **Eloquent Integration**: Intelligently uses your application's Eloquent models (e.g., `\\App\\Models\\Sale`) when available.
- **Flexible Output**: Returns results as JSON or HTML tables. HTML reports can be printed to PDF using browser's print function.
- **Multi-Provider Support**: Works with OpenAI, OpenRouter, and Ollama (local LLMs).
- **Highly Configurable**: Fine-tune schema visibility, model scanning, and auto-imports.

---

� How It Works Internally
-------------------------

[](#-how-it-works-internally)

```
User Prompt
   ↓
PromptBuilder → AI Model
   ↓
JSON Query Definition
   ↓
Validator (read-only, method whitelist)
   ↓
Interpreter → Laravel Query Builder
   ↓
Result (HTML / JSON)

```

---

�📦 Installation
---------------

[](#-installation)

1. **Require the package** via Composer:

    ```
    composer require nalrep/laravel
    ```
2. **Publish the configuration** file:

    ```
    php artisan vendor:publish --tag=config --provider="Nalrep\\NalrepServiceProvider"
    ```

---

⚙️ Configuration
----------------

[](#️-configuration)

The configuration file `config/nalrep.php` gives you full control over how Nalrep behaves.

### 1. AI Provider

[](#1-ai-provider)

Choose your AI driver. Supported drivers: `openai`, `openrouter`, `ollama`.

```
'driver' => env('NALREP_DRIVER', 'openai'),

'openai' => [
    'api_key' => env('OPENAI_API_KEY'),
    'model' => env('NALREP_OPENAI_MODEL', 'gpt-4o-mini'), // Required
],

'openrouter' => [
    'api_key' => env('OPENROUTER_API_KEY'),
    'model' => env('NALREP_OPENROUTER_MODEL', 'openai/gpt-4o-mini'), // Required
],
```

**Example Models:**

- `gpt-4o-mini` - Fast and cost-effective (recommended for most use cases)
- `gpt-4o` - More powerful for complex queries
- `o3-mini` - Optimized for code generation

### 2. Request Timeout

[](#2-request-timeout)

Set the maximum duration for AI requests to prevent hanging processes.

```
// Timeout in seconds (default: 120)
'timeout' => env('NALREP_TIMEOUT', 120),
```

### 3. Schema Exclusion

[](#3-schema-exclusion)

Control which database tables are visible to the AI. This is crucial for security and token optimization.

```
// Tables to exclude from the schema sent to the AI
'excluded_laravel_tables' => [
    'migrations', 'failed_jobs', 'password_reset_tokens', 'sessions',
    'cache', 'cache_locks', 'jobs', 'job_batches', 'sqlite_sequence'
],

'excluded_tables' => [
    'admin_users', 'audit_logs', 'sensitive_data'
],
```

### 4. Model Scanning

[](#4-model-scanning)

Nalrep scans your application for Eloquent models to help the AI write cleaner, more "Laravel-like" queries using your actual classes.

```
// Directories to scan for Eloquent models
'model_paths' => [
    'app/Models',
],
```

*The AI is instructed to use the Fully Qualified Class Name (FQCN) (e.g., `\\App\\Models\\User`) to avoid "Class Not Found" errors.*

### 5. Common Classes (Auto-Imports)

[](#5-common-classes-auto-imports)

Define classes that should be automatically available in the generated code execution environment. This prevents common "Class not found" errors.

```
'common_classes' => [
    'Carbon\\Carbon',
    'Illuminate\\Support\\Facades\\DB',
    // Add any other classes your queries might need
],
```

*These classes will be automatically available when executing queries, allowing the AI to use them without import statements.*

### 6. Frontend Component Settings

[](#6-frontend-component-settings)

Configure the input component behavior and available formats.

```
'allowed_formats' => ['html', 'json', 'pdf'], // Formats available in the dropdown
'example_prompts' => [
    'Total sales last month',
    'Top 5 customers by revenue',
    'New users this week',
],
```

### 7. Safety Settings

[](#7-safety-settings)

Configure the safety guardrails.

```
'safety' => [
    'allow_destructive' => false, // MUST be false in production. Blocks DELETE, UPDATE, DROP, etc.
    'max_rows' => 1000,           // Limit result set size to prevent memory exhaustion.
],
```

---

🔒 Security Architecture
-----------------------

[](#-security-architecture)

Nalrep takes security seriously. We use a **JSON-based Query Interpreter** to ensure safe execution.

### 1. No `eval()`

[](#1-no-eval)

We do **not** use PHP's `eval()` function. Instead, the AI generates a structured JSON definition of the query (e.g., `{"method": "where", "args": [...]}`). This JSON is parsed and executed by a strict interpreter that only allows valid Query Builder methods.

### 2. Read-Only Enforcement

[](#2-read-only-enforcement)

The **Validator** inspects the JSON structure before execution and blocks any destructive methods such as `delete`, `update`, `insert`, `drop`, or `truncate`.

### 3. Schema Filtering

[](#3-schema-filtering)

By using `excluded_tables`, you ensure that the AI never sees the structure of sensitive tables.

### 4. Static Date Generation

[](#4-static-date-generation)

The AI is provided with the current date and generates static date strings (e.g., "2024-01-01"), eliminating the need to execute arbitrary PHP date logic.

---

💻 Usage
-------

[](#-usage)

### Blade Component

[](#blade-component)

The easiest way to use Nalrep is via the provided Blade component. It renders a simple input form for users to type their request.

```

```

### Customizing the View

[](#customizing-the-view)

You can publish the views to customize the frontend component:

```
php artisan vendor:publish --tag=views --provider="Nalrep\\NalrepServiceProvider"
```

This will publish the views to `resources/views/vendor/nalrep`. You can edit `components/input.blade.php` to match your application's design.

### Programmatic Usage

[](#programmatic-usage)

You can use the `Nalrep` facade to generate reports programmatically in your controllers or commands.

```
use Nalrep\\Facades\\Nalrep;

public function report()
{
    $prompt = "Show me the total sales for each product in 2024";

    // Returns HTML string of the report table
    $html = Nalrep::generate($prompt, 'html');

    return view('reports.show', compact('html'));
}
```

---

⚠️ Error Handling
-----------------

[](#️-error-handling)

Nalrep provides comprehensive error handling to help developers and users understand what went wrong.

### Exception Types

[](#exception-types)

Nalrep throws specific exceptions for different error scenarios:

```
use Nalrep\Exceptions\{
    NalrepException,           // Base exception
    VaguePromptException,      // Prompt is too unclear
    InvalidPromptException,    // Prompt not related to data reporting
    QueryGenerationException,  // Cannot generate valid query
    InvalidJsonException,      // AI returned malformed JSON
    ValidationException        // Query failed security validation
};
```

### Handling Errors in Your Code

[](#handling-errors-in-your-code)

```
use Nalrep\Facades\Nalrep;
use Nalrep\Exceptions\VaguePromptException;
use Nalrep\Exceptions\InvalidPromptException;

try {
    $report = Nalrep::generate($userPrompt, 'html');
} catch (VaguePromptException $e) {
    // User's query was too vague
    return back()->with('error', $e->getMessage());
} catch (InvalidPromptException $e) {
    // User's query wasn't related to data reporting
    return back()->with('error', 'Please ask for a data report or query.');
} catch (\Nalrep\Exceptions\NalrepException $e) {
    // Any other Nalrep-specific error
    \Log::warning('Nalrep error', ['message' => $e->getMessage()]);
    return back()->with('error', 'Unable to generate report. Please try rephrasing your query.');
}
```

### How Errors Are Surfaced

[](#how-errors-are-surfaced)

**In Development (`APP_DEBUG=true`):**

- Full error messages are displayed
- Stack traces are available in logs
- JSON responses include detailed error information

**In Production (`APP_DEBUG=false`):**

- User-friendly error messages are shown
- Technical details are logged but not exposed
- Generic fallback messages for unexpected errors

### AI Error Detection

[](#ai-error-detection)

The AI is instructed to detect and report issues:

- **Vague Prompts**: "Show me data" → AI returns `vague_prompt` error
- **Invalid Requests**: "What's the weather?" → AI returns `invalid_prompt` error
- **Schema Mismatch**: "Show sales from products table" (when table doesn't exist) → AI returns `query_generation_failed` error

### Example Error Responses

[](#example-error-responses)

**JSON Format:**

```
{
  "error": true,
  "type": "VaguePromptException",
  "message": "Your query is too vague. Please be more specific about what data you want to see."
}
```

**HTML Format:**

```

  Unable to generate report: Your query is too vague...

```

---

🔌 Extensibility
---------------

[](#-extensibility)

### Custom AI Agents

[](#custom-ai-agents)

You can implement your own AI driver by implementing the `Nalrep\\Contracts\\Agent` interface and registering it in the config.

```
use Nalrep\\Contracts\\Agent;
use Nalrep\\AI\\PromptBuilder;

class MyCustomAgent implements Agent {
    protected $schema;
    protected $models;

    public function setSchema(array $schema): Agent {
        $this->schema = $schema;
        return $this;
    }

    public function setModels(array $models): Agent {
        $this->models = $models;
        return $this;
    }

    public function generateQuery(string $prompt, string $mode = 'builder'): string {
        // Use the built-in PromptBuilder
        $promptBuilder = new PromptBuilder();

        // Optionally add custom instructions
        $promptBuilder->appendCustomInstructions(
            "Always include a summary row at the end of results."
        );

        $systemPrompt = $promptBuilder->build(
            $this->schema,
            $this->models,
            date('Y-m-d')
        );

        // Send to your custom AI model (e.g., local Ollama, Anthropic, etc.)
        $aiCompletion = $this->myAiService->complete($systemPrompt, $prompt);

        // Return the JSON query definition from the AI
        return $aiCompletion;
    }
}

// config/nalrep.php
'driver' => MyCustomAgent::class,
```

### Using PromptBuilder Standalone

[](#using-promptbuilder-standalone)

Developers can also use the `PromptBuilder` class directly for custom implementations:

```
use Nalrep\\AI\\PromptBuilder;

$builder = new PromptBuilder();

// Get just the base prompt
$basePrompt = $builder->getBasePrompt();

// Or build the complete prompt
$fullPrompt = $builder->build($schema, $models, date('Y-m-d'));

// Add custom instructions
$builder->appendCustomInstructions("Focus on performance optimization.");
$customPrompt = $builder->build($schema, $models, date('Y-m-d'));
```

---

📄 License
---------

[](#-license)

The MIT License (MIT).

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance69

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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

180d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/93cb331312a2514e580b3182e28c78d8731ded0f1c2c89d54e2cf7a1b6ba6ee1?d=identicon)[arhinful](/maintainers/arhinful)

---

Top Contributors

[![arhinful](https://avatars.githubusercontent.com/u/43961320?v=4)](https://github.com/arhinful "arhinful (18 commits)")

---

Tags

laraveldatabaseaisqleloquentreportingopenaiquery buildernlpllmnatural-language

### Embed Badge

![Health badge](/badges/nalrep-laravel/health.svg)

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

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[eusonlito/laravel-database-cache

Cache Database Query results on Laravel Query Builder or Eloquent

194.2k](/packages/eusonlito-laravel-database-cache)[sarfraznawaz2005/indexer

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

562.7k](/packages/sarfraznawaz2005-indexer)[toponepercent/baum

Baum is an implementation of the Nested Set pattern for Eloquent models.

3154.7k](/packages/toponepercent-baum)

PHPackages © 2026

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