PHP code example of prolaxu / laravel-intentql

1. Go to this page and download the library: Download prolaxu/laravel-intentql library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

prolaxu / laravel-intentql example snippets


$result = IntentQL::for(Order::class)
    ->allowFields(['id', 'agent_id', 'status', 'total', 'created_at'])
    ->prompt('Show completed orders this month grouped by agent with revenue')
    ->get();

return [
    'provider' => env('INTENTQL_PROVIDER', 'gemini'),

    'providers' => [
        'gemini' => [
            'driver' => 'gemini',
            'api_key' => env('GEMINI_API_KEY'),
            'model' => env('GEMINI_MODEL', 'gemini-2.5-flash'),
            'base_url' => env('GEMINI_BASE_URL', 'https://generativelanguage.googleapis.com'),
        ],
        'openai' => [...],
        'ollama' => [...],
    ],

    'limits' => [
        'max_results' => 1000,
        'default_results' => 100,
        'max_select' => 50,
        'max_filters' => 25,
        'max_group_by' => 10,
        'max_aggregates' => 10,
        'max_having' => 10,
        'max_sort' => 5,
        'max_relation_filters' => 5,
        'max_relation_depth' => 2,
        'max_filter_depth' => 5,
        'max_in_values' => 100,
        'max_value_length' => 500,
    ],

    'security' => [
        'denied_fields' => ['password', 'remember_token', 'api_token', ...],
        'exclude_hidden' => true,
    ],

    'relations' => ['auto_discover' => true],

    'dates' => [
        'timezone' => env('INTENTQL_TIMEZONE'),
        'week_starts_at' => 'monday',
    ],

    'cache' => [
        'enabled' => true,
        'store' => null,
        'ttl' => 3600,
        'prefix' => 'intentql_schema:',
    ],
];

$result = IntentQL::across([Order::class, Invoice::class, Ticket::class, Deal::class])
    ->ask('Top 10 customers by revenue this year')
    ->get();

$result->model();   // App\Models\Invoice — the source that answered

use Prolaxu\IntentQL\Runtime\EntityCandidate;

IntentQL::across([
    new EntityCandidate(
        model: Order::class,
        name: 'orders',
        label: 'Sales orders',
        description: 'Customer orders: status, totals, agent, dates.',
        constraints: (new QueryConstraints)->denyingFields(['internal_cost']),
    ),
    new EntityCandidate(model: Ticket::class, name: 'tickets'),
])->ask('Revenue by agent this month')->get();

use Prolaxu\IntentQL\Facades\IntentQL;

$result = IntentQL::for(Order::class)
    ->ask('Show completed orders above 5000 this month grouped by agent')
    ->get();

$result->data();        // Collection of rows
$result->definition();  // the validated QueryDefinition
$result->sql();         // the compiled SQL
$result->bindings();    // the bound values

$query = IntentQL::for(Order::class)
    ->prompt('Top 10 customers by revenue this year')
    ->compile();

$query->builder();   // Illuminate\Database\Eloquent\Builder — chain onto it freely
$query->toSql();
$query->bindings();

protected $casts = ['status' => OrderStatus::class];   // enum OrderStatus: int { case COMPLETED = 12; }

$metadata = IntentQL::inspect(Order::class);

$metadata->table;                      // 'orders'
$metadata->primaryKey;                 // 'id'
$metadata->field('total')->logicalType; // FieldType::NUMBER
$metadata->field('total')->cast;        // 'decimal:2'
$metadata->relationNames();             // ['customer', 'agent', 'items']

enum FieldType: string {
    case STRING; case INTEGER; case NUMBER; case BOOLEAN;
    case DATE; case DATETIME; case JSON; case UUID; case ENUM;
}

IntentQL::for(Order::class)
    ->allowFields(['status', 'total', 'created_at', 'agent_id'])
    ->denyFields(['internal_cost', 'deleted_at'])
    ->prompt('Revenue by agent this month')
    ->get();

public function customer(): BelongsTo   // discovered
public function explode()               // never called — no Relation return type

IntentQL::for(Order::class)
    ->allowRelations(['customer', 'agent', 'items.product'])
    ->ask('Show completed orders where customer country is Nepal')
    ->get();

public function intentqlRelations(): array
{
    return ['customer', 'agent', 'items.product'];
}

// "Show customers with more than 5 orders"
['relation' => 'orders', 'count_operator' => '>', 'count' => 5]

'aggregates' => [
    ['function' => 'count', 'field' => 'id',    'as' => 'total_orders'],
    ['function' => 'sum',   'field' => 'total', 'as' => 'revenue'],
],
'having' => [['alias' => 'total_orders', 'operator' => '>', 'value' => 5]],

$query->whereBetween('created_at', [now()->startOfMonth(), now()->endOfMonth()]);

use Prolaxu\IntentQL\Support\{Clock, FrozenClock};

app()->instance(Clock::class, new FrozenClock('2026-03-15 13:45:00'));

$explanation = IntentQL::for(Order::class)
    ->prompt('Top 10 agents by completed revenue this month')
    ->explain();

[
    'query'    => QueryDefinition,  // Arrayable + JsonSerializable
    'sql'      => 'select "orders"."agent_id", SUM("orders"."total") as "revenue" ...',
    'bindings' => ['completed', '2026-03-01 00:00:00', '2026-03-31 23:59:59'],
]

IntentQL::for(Order::class)->ask('Show users; DROP TABLE users;')->get();
// The text stays a prompt. Nothing derived from it becomes SQL.

interface LanguageModel
{
    public function generate(QueryPrompt $prompt): AiResponse;
    public function name(): string;
}

IntentQL::extend('claude', fn (array $config, Container $app) => new ClaudeProvider(
    $app->make(HttpFactory::class),
    $config['api_key'],
));

IntentQL::for(Order::class)->provider('claude')->prompt(...)->get();

use Prolaxu\IntentQL\Validation\Contracts\QueryPolicy;

final class TenantQueryPolicy implements QueryPolicy
{
    public function authorize(QueryContext $context, QueryDefinition $query): void
    {
        if (! $context->user?->can('run-reports')) {
            throw UnauthorizedQueryException::make('reporting is not enabled for this user.');
        }
    }
}

$this->app->bind(QueryPolicy::class, TenantQueryPolicy::class);

IntentQL::for(Order::class)
    ->prompt('Revenue this month')
    ->scope(fn (Builder $query) => $query->where('tenant_id', auth()->user()->tenant_id))
    ->get();

interface QueryCompiler
{
    public function compile(QueryDefinition $definition, EntityMetadata $entity): CompiledQuery;
}

$this->app->bind(QueryCompiler::class, MyCompiler::class);

Prolaxu\IntentQL\Events\QueryPlanned   // context, definition, AiResponse (with token usage)
Prolaxu\IntentQL\Events\QueryExecuted  // context, compiled query, row count, duration in ms

IntentQL::clearSchemaCache(Order::class);
IntentQL::clearSchemaCache();

use Prolaxu\IntentQL\Facades\IntentQL;

$planner = IntentQL::fake([[
    'entity' => 'orders',
    'select' => ['agent_id'],
    'group_by' => ['agent_id'],
    'aggregates' => [['function' => 'sum', 'field' => 'total', 'as' => 'revenue']],
]]);

$result = IntentQL::for(Order::class)->ask('Revenue by agent')->get();

expect($result->count())->toBe(2);
expect($planner->lastPrompt()->schema['fields'])->not->toContain('internal_cost');
bash
php artisan vendor:publish --tag=intentql-config