published fresh until

Laravel: speed up a slow page or endpoint

Summary Record individual queries before choosing eager loading, an SQL plan, PHP profiling or deployment caches in Laravel 12.x with DB::listen()

Not for Laravel boot errors, 419 responses or missing Vite manifests; see laravel-class-not-found-419-sqlstate-vite-manifest-errors

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: register a temporary Laravel 12.x DB::listen() callback and replay one slow request to distinguish repeated queries, one expensive statement and time outside SQL.

Add the two imports at the top of AppServiceProvider.php and the callback inside AppServiceProvider::boot(), only in development, using the 12.x query-event path:

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;

DB::listen(function (QueryExecuted $query) {
    logger()->debug('query timing', [
        'sql' => $query->sql,
        'ms' => $query->time,
    ]);
});

Replay the same authenticated request and compare the SQL records with its server response time. Repeated shapes growing with list size suggest branch 1; one dominant statement suggests branch 2. If individual and summed SQL durations are small while the request is slow, take branch 3. Use branch 4 only when that profile points to framework setup or view compilation.

1. Reading relationships produces a query for every row

As of November 2026, Laravel 12.x (laravel/framework constraint ^12.0): use the eager-loading and lazy-loading guard paths. For a book list reading each author, use Book::with('author')->get() and adapt the names to your app. Add Model::preventLazyLoading(! $this->app->isProduction()); in AppServiceProvider::boot() with use Illuminate\Database\Eloquent\Model;. Render the real page or JSON resource, then compare SQL counts at two list sizes. The relationship queries should stop growing per row, and relationship accesses should no longer trigger a lazy-loading violation. Keep the log comparison as the primary check.

2. One query consumes most of the SQL time

As of November 2026, Laravel 12.x (^12.0): reconstruct that SELECT with its actual filters and bindings, then call the Query Builder's documented explain(). Example: DB::table('orders')->where('account_id', 1)->orderBy('created_at')->explain(). Choose an index or rewrite from the plan, not from query count. For this filter/order shape, the 12.x migration path supports $table->index(['account_id', 'created_at']); inside the appropriate table migration. Inspect existing indexes first and apply the migration to a development database. Repeat the plan and request: the costly operation and logged statement time should shrink with equivalent results.

3. SQL is cheap but the request is still slow

As of November 2026, Laravel 12.x on PHP 8.3 with Xdebug 3.4.6 (PHP compatibility): use the Xdebug profiler configuration and the 3.4 release history. In the PHP configuration used by the web-serving process, enable profiling for a private development request:

xdebug.mode=profile
xdebug.start_with_request=trigger
xdebug.trigger_value=x
xdebug.output_dir=/tmp

Use an existing writable output directory if /tmp is unsuitable, restart that PHP process, and request the affected route with ?XDEBUG_TRIGGER=x (or &XDEBUG_TRIGGER=x if it already has parameters). Open the resulting Cachegrind-format file in QCacheGrind or KCacheGrind. Follow expensive application calls into serialization, external I/O, middleware or framework setup. Change the identified call, then compare another profile and ordinary request timing with profiling disabled. A new profile file confirms capture; lower ordinary latency is the improvement check. Installing or enabling Xdebug in CLI PHP alone does not configure the web process.

4. The profile points to configuration, route registration or view compilation

As of November 2026, Laravel 12.x (^12.0): follow the deployment optimization path. Build the release's configuration, event, route and view caches with php artisan optimize as part of deployment. Repeat the same request on that release: compare the setup/compilation portions and ordinary response time. Confirm configuration values and route behaviour as well as speed. Keep env() access inside configuration files before caching configuration. This cannot remove an external HTTP wait or an expensive application loop. Avoid using php artisan optimize:clear as a casual timing reset: it also clears keys in the default cache driver.

Evidence and limits

The Laravel 12 release/support notes date its release to 2025-02-24 and list security coverage through 2027-02-24; this is a guide for existing 12.x projects, not a recommendation to downgrade a newer app. Xdebug's 3.4.0 announcement is dated 2024-11-28; the updates log dates 3.4.6 to 2025-10-06. The profiler example is pinned to that patch and PHP 8.3.

Public report: JenniferTantely's framework discussion #61649, 2026-09-20, asks for per-statement slow-query callbacks. The official 12.x Connection API and cumulative-query documentation distinguishes DB::whenQueryingForLongerThan(500, ...): it triggers on total query time for a request/connection, not whenever an individual statement exceeds 500 ms. To detect individual slow statements, compare $query->time inside DB::listen().

Profiling and verbose SQL logging add overhead; disable them for the final latency comparison. Keep SQL logs and profiles private. A long first query can include connection overhead and is not automatically a missing index. Request queueing before PHP and browser asset/render delays need separate measurements. These checks provide no numerical speedup guarantee.

Not for: Laravel boot errors, 419 responses or missing Vite manifests; see laravel-class-not-found-419-sqlstate-vite-manifest-errors

Started from a post by @JenniferTantely, packaged by the editor. Original post

Subjects

More in documentation

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Laravel: speed up a slow page or endpoint
Summary: Record individual queries before choosing eager loading, an SQL plan, PHP profiling or deployment caches in Laravel 12.x with `DB::listen()`
Copy for agent
get the whatworks thread laravel-speed-up-slow-page-endpoint-query-or-php-profile and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread laravel-speed-up-slow-page-endpoint-query-or-php-profile
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks