PHPackages                             omaresmael/laravel-query-optimizer - 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. omaresmael/laravel-query-optimizer

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

omaresmael/laravel-query-optimizer
==================================

An AI powered optimizer for laravel eloquent and query builder

1.0.0(3y ago)110MITPHP

Since Mar 26Pushed 3y ago1 watchersCompare

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

READMEChangelog (3)Dependencies (7)Versions (4)Used By (0)

laravel-query-optimizer
=======================

[](#laravel-query-optimizer)

Optimize laravel DB or eloquent read queries using openAI API, and get insights on how you can make your queries faster

 [![Laravel Version](https://camo.githubusercontent.com/460683f883dde5a82adc43aae553a11b92b73204ef9668edece3778729cac991/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302d6f72616e6765)](https://camo.githubusercontent.com/460683f883dde5a82adc43aae553a11b92b73204ef9668edece3778729cac991/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302d6f72616e6765) [![Total Downloads](https://camo.githubusercontent.com/6cb923560bac14426e63f1a5516d94922e57c1ef251f7f4ed3a1a58f260bcf36/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f6d617265736d61656c2f6c61726176656c2d71756572792d6f7074696d697a6572)](https://packagist.org/packages/omaresmael/laravel-query-optimizer) [![Latest Version](https://camo.githubusercontent.com/1f2d8d2611e232468a590e42afa3e42d9d46357b4a54ef3a765b8fd102d62abf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6d617265736d61656c2f6c61726176656c2d71756572792d6f7074696d697a6572)](https://packagist.org/packages/omaresmael/laravel-query-optimizer)

Installation
============

[](#installation)

First, install the package using composer

```
composer require omaresmael/laravel-query-optimizer --dev
```

Then, publish openAI configuration file

```
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
```

Lastly, add the openAPI key to your `.env` file

```
OPENAI_API_KEY=sk-...
```

and that's it, you are ready to go

Usage
=====

[](#usage)

this package can help you optimize your eloquent or DB queries using openAI

```
User::query() //can be applied to `DB facade` as well (see tests)
    ->select('users.id', 'users.name')
    ->whereHas('roles', function ($query) {
        $query->where('name', 'author');
    })
    ->whereHas('posts', function ($query) {
        $query->where('title', 'Awesome post');
    })->optimize()->get();
```

**the package has the following methods**

### `optimize()`

[](#optimize)

This method is responsible for optimizing the query and return an instance of the `Optimizer` class.

```
User::query()
   ->select('users.id', 'users.name')
    ->whereHas('roles', function ($query) {
        $query->where('name', 'author');
    })
    ->whereHas('posts', function ($query) {
        $query->where('title', 'Awesome post');
    })->optimize();

//old query => select `id`, `name` from `users` where exists (select * from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `users`.`id` = `role_user`.`user_id` and `type` = ?) and exists (select * from `posts` where `users`.`id` = `posts`.`user_id` and `title` = ?)

//optimized query => SELECT `id`, `name` FROM `users` INNER JOIN `role_user` ON `users`.`id` = `role_user`.`user_id` INNER JOIN `roles` ON `roles`.`id` = `role_user`.`role_id` INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id` WHERE `type` = ? AND `title` = ?

```

### `toSql()`

[](#tosql)

this method will return the optimized query as a string

```
User::query()
    ->select('users.id', 'users.name')
    ->whereHas('roles', function ($query) {
        $query->where('type', 'author');
    })
    ->whereHas('posts', function ($query) {
        $query->where('title', 'Awesome post');
    })->optimize()->toSql();

//output => SELECT `id`, `name` FROM `users` INNER JOIN `role_user` ON `users`.`id` = `role_user`.`user_id` INNER JOIN `roles` ON `roles`.`id` = `role_user`.`role_id` INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id` WHERE `type` = ? AND `title` = ?

```

### `get()`

[](#get)

this method will run the optimized query that is generated by `optimize()` method and return the result

⚠️ make sure to know the query you are running before using this method, as it will run the optimized query and not the original query

```
    User::query()
    ->select('users.id', 'users.name')
    ->whereHas('roles', function ($query) {
        $query->where('type', 'author');
    })
    ->whereHas('posts', function ($query) {
        $query->where('title', 'Awesome post');
    })->optimize()->get()->toArray();

    //output => ['id' => '1', 'name' => 'omar']
```

### `explain()`

[](#explain)

this method will return a key-value array that contains the optimized query, the reasoning behind performing such optimization, and suggestions to manually optimize the query even further

```
User::query()
    ->select('users.id', 'users.name')
    ->whereHas('roles', function ($query) {
        $query->where('type', 'author');
    })
    ->whereHas('posts', function ($query) {
        $query->where('title', 'Awesome post');
    })->optimize()->explain();
```

the array format will be

```
[
'optimizedQuery' => 'SELECT `id`, `name` FROM `users` INNER JOIN `role_user` ON `users`.`id` = `role_user`.`user_id` INNER JOIN `roles` ON `roles`.`id` = `role_user`.`role_id` INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id` WHERE `type` = ? AND `title` = ?' // the optimized query
'reasoning'      => 'This query optimizes the original query by using JOINs to reduce the number of subqueries and improve the performance of the query. By using JOINs, the query can access the data from multiple tables in a single query, instead of having to make multiple subqueries.' //the reasoning behind performing such optimization,
'suggestions'    => 'It may be beneficial to add an index on the `type` and `title` columns to further improve the performance of the query.' //suggestions to manually optimize the query even further
]
```

Credits
-------

[](#credits)

[Omar Esmaeel](https://github.com/omaresmael)

License
-------

[](#license)

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

Inspiration
-----------

[](#inspiration)

This package is inspired by [laravel-ask-database](https://github.com/beyondcode/laravel-ask-database) package
Thanks for the great work [Marcel Pociot](https://github.com/mpociot)

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

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

Total

3

Last Release

1139d ago

Major Versions

0.0.7 → 1.0.02023-03-30

### Community

Maintainers

![](https://www.gravatar.com/avatar/10cb22dd603df7b6d46ba7e8dd60a42de132d012f172097176c399c215b10ef5?d=identicon)[omaresmael](/maintainers/omaresmael)

---

Top Contributors

[![omaresmael](https://avatars.githubusercontent.com/u/33787232?v=4)](https://github.com/omaresmael "omaresmael (38 commits)")

---

Tags

aidatabaseeloquentlaraveloptimizationlaraveldatabaseopenaioptimizationPerformace

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/omaresmael-laravel-query-optimizer/health.svg)

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

###  Alternatives

[nunomaduro/laravel-optimize-database

Publishes migrations that make your database production ready.

26123.0k](/packages/nunomaduro-laravel-optimize-database)[halilcosdu/laravel-slower

Laravel Slower: Optimize Your DB Queries with AI

40022.0k](/packages/halilcosdu-laravel-slower)[sarfraznawaz2005/indexer

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

562.7k](/packages/sarfraznawaz2005-indexer)[hpolthof/laravel-translations-db

A database translations implementation for Laravel 5.

545.8k](/packages/hpolthof-laravel-translations-db)[cubettech/lacassa

Cassandra based query builder for laravel.

358.5k](/packages/cubettech-lacassa)

PHPackages © 2026

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