PHPackages                             jumamiller/optimize-laravel-query - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. jumamiller/optimize-laravel-query

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jumamiller/optimize-laravel-query
=================================

An AI powered optimizer for laravel eloquent and query builder

114PHP

Since Jul 18Pushed 2y ago1 watchersCompare

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

READMEChangelogDependenciesVersions (2)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 jumamiller/optimize-laravel-query --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)

[Miller Juma](https://github.com/jumamiller)

License
-------

[](#license)

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

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

[](#inspiration)

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity23

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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/250774e60621fbf0e423320d970d3323f890d1cc209858c28822c76b5c33e63c?d=identicon)[jumamiller](/maintainers/jumamiller)

---

Top Contributors

[![jumamiller](https://avatars.githubusercontent.com/u/50165600?v=4)](https://github.com/jumamiller "jumamiller (1 commits)")

### Embed Badge

![Health badge](/badges/jumamiller-optimize-laravel-query/health.svg)

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

###  Alternatives

[webarchitect609/bitrix-user-type

Set of custom Bitrix user property types and basic auxiliary functionality to help develop new types as easy and fast as it possible.

1418.4k1](/packages/webarchitect609-bitrix-user-type)

PHPackages © 2026

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