Package

Halilcosdu Laravel Slower

Laravel Slower: Optimize Your DB Queries with AI

Package

halilcosdu/laravel-slower

View on GitHub →

Laravel Slower: Optimize Your DB Queries with AI

Laravel Slower is a powerful package designed for Laravel developers who want to enhance the performance of their applications. It intelligently identifies slow database queries and leverages AI to suggest optimal indexing strategies and other performance improvements. Whether you're debugging or routinely monitoring your application, Laravel Slower provides actionable insights to streamline database interactions.

Installation

You can install the package via composer:

composer require halilcosdu/laravel-slower

You can publish and run the migrations with:

php artisan vendor:publish --tag="slower-migrations"
php artisan migrate
public function up()
{
    Schema::create(config('slower.resources.table_name'), function (Blueprint $table) {
        $table->id();
        $table->boolean('is_analyzed')->default(false)->index();
        $table->string('bindings');
        $table->longtext('sql');
        $table->unsignedInteger('time')->index();
        $table->string('connection');
        $table->string('connection_name');
        $table->longtext('raw_sql');
        $table->longtext('recommendation')->nullable();

        $table->timestamps();
    });
}

public function down(): void
{
    Schema::dropIfExists(config('slower.resources.table_name'));
}

You can publish the config file with:

php artisan vendor:publish --tag="slower-config"

This is the contents of the published config file:

    'enabled' => env('SLOWER_ENABLED', true),
    'threshold' => env('SLOWER_THRESHOLD', 10000),
    'resources' => [
        'table_name' => (new SlowLog)->getTable(),
        'model' => SlowLog::class,
    ],
    'ai_recommendation' => env('SLOWER_AI_RECOMMENDATION', true), // You can completely disable AI, and then the package will only log slow queries to the database.
    'recommendation_model' => env('SLOWER_AI_RECOMMENDATION_MODEL', 'gpt-4'),
    'open_ai' => [
        'api_key' => env('OPENAI_API_KEY'),
        'organization' => env('OPENAI_ORGANIZATION'),
        'request_timeout' => env('OPENAI_TIMEOUT'),
    ],
    'prompt' => env('SLOWER_PROMPT',"As a distinguished database optimization expert, your expertise is invaluable for refining SQL queries to achieve maximum efficiency. Please examine the SQL statement provided below. Based on your analysis, could you recommend sophisticated indexing techniques or query modifications that could significantly improve performance and scalability?")
];

Usage

You can register the commands with your scheduler.

php artisan slower:clean /*{days=15}  Delete records older than 15 days.*/
php artisan slower:analyze /*Analyze the records where is_analyzed=false*/
    protected $commands = [
        AnalyzeQuery::class,
        SlowLogCleaner::class,
    ];

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command(AnalyzeQuery::class)->runInBackground()->daily();
        $schedule->command(SlowLogCleaner::class)->runInBackground()->daily();
    }
$model = \HalilCosdu\Slower\Models\SlowLog::first();

\HalilCosdu\Slower\Facades\Slower::analyze($model): Model;

dd($model->raw_sql); /*select count(*) as aggregate from "product_prices" where "product_id" = '1' and "price" = '0' and "discount_total" > '0'*/

dd($model->recommendation);

Example Recommendation

In order to improve database performance and scalability, here are some suggestions below:

  1. Indexing: Effective database indexing can significantly speed up query performance. For your query, consider adding a combined (composite) index on product_id, price, and discount_total. This index would work well because the where clause covers all these columns.
CREATE INDEX idx_product_prices
ON product_prices (product_id, price, discount_total);

(Note: The order of the columns in the index might depend on the selectivity of the columns and the data distribution. Therefore, you might have to reorder them depending on your specific situation.)

  1. Data Types: Ensure that the values being compared are of appropriate data types. Comparing or converting inappropriate data types at run time will slow down the search. It appears that you're using string comparisons ('1') for product_id, price, and discount_total which are likely numerical columns. Remove the quotes for these where clause conditions.

Updated Query:

SELECT COUNT(*) AS aggregate
FROM product_prices
WHERE product_id = 1
AND price = 0
AND discount_total > 0;
  1. ANALYZE: Another practice to improve query performance could be running the ANALYZE command. This command collects statistics about the contents of tables in the database, and stores the results in the pg_statistic system catalog. Subsequently, the query planner uses these statistics to help determine the most efficient execution plans for queries.
ANALYZE product_prices;

Remember to periodically maintain your index to keep up with the CRUD operations that could lead to index fragmentation. Depending on your DBMS, you might want to REBUILD or REORGANIZE your indices.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Halilcosdu Laravel Slower Related Articles

Optimize Your Eloquent Queries with AI image

Optimize Your Eloquent Queries with AI

Read article
Replicate Laravel PHP Client image

Replicate Laravel PHP Client

Read article
Create an Animated Scrolling Card with Tailwind image

Create an Animated Scrolling Card with Tailwind

Read article
18 Tips to Optimize Your Laravel Database Queries image

18 Tips to Optimize Your Laravel Database Queries

Read article
Neya on switching back to Rails image

Neya on switching back to Rails

Read article
PostgreSQL vs. MongoDB for Laravel: Choosing the Right Database image

PostgreSQL vs. MongoDB for Laravel: Choosing the Right Database

Read article

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm

Let your users buy domains without leaving your app

If your Laravel app gives users a site, a storefront, or a workspace, they’ll eventually want their own domain. The name.com API lets them search, register, and connect one without leaving your product. It’s a clean REST API, so Laravel’s HTTP client is all you need.

Let your users buy domains without leaving your app

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift