Skip to main content

Cloudsoft Zone Build, deploy and scale with practical guides to PHP, Node.js, React, DevOps and AI automation. Explore the guides

Cloudsoft Zone
DevOpsLaravelMySQLPHPTroubleshooting guide

Slow MySQL queries in Laravel: diagnose the complete request before tuning

Find slow MySQL queries in Laravel by separating individual query time, cumulative database work, lock waits and application overhead before choosing a measured correction.

Nilesh Kushvaha

4 min read

Sourced MySQL text artwork with a Laravel slow-query diagnosis workflow from request timing to verified correction.
Image: Cloudsoft Zone layout; Oracle Corporation; vectorized by VulcanSphere / Public domain (text logo); trademark retained
In this article

An order page takes several seconds to render, but the database's slow log shows no obvious culprit. The request executes dozens of moderate queries while serializing related models, then waits on an external service.

Slow MySQL queries in Laravel should be investigated inside the complete request budget. Separate query duration, query count, lock waiting and non-database work before changing server limits or adding indexes.

Our Laravel N+1 guide covers repeated relationship loading. This companion connects that pattern to request timing, database evidence and correction verification.

A Laravel request has application and acquisition time, database work, and post-query processing.
Do not attribute every millisecond of HTTP latency to the SQL plan.

Step 1: Define the slow workflow and observation window

Record the route template, authorized data scope, representative parameters and release identifier. Compare equivalent operations rather than a tiny development fixture with a large production report.

Measure total request latency and the application's database contribution. Include connection acquisition and external calls where the instrumentation distinguishes them.

Observation Possible next investigation
Many moderate queries Repeated work or N+1 relationship access
One expensive query Plan, filtering, indexes and data volume
Query waits unpredictably Locks, transactions or resource contention
Database time is small Application processing or external dependency

Do not weaken tenant filters or authorization to reproduce a faster request. The performance target is the correct authorized result.

Step 2: Add bounded Laravel timing evidence

Use the existing application's query-event owner. This fragment emits only a duration and stable category for a single query crossing an illustrative threshold:

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

DB::listen(function (QueryExecuted $query): void {
    if ($query->time < 200) {
        return;
    }

    Log::warning('database.query_slow', [
        'duration_ms' => $query->time,
        'code' => 'QUERY_TIME_THRESHOLD',
    ]);
});

Register it through the existing provider lifecycle, not inside every request. The two-hundred-millisecond value is an example, not a universal service objective. Bound sampling or rate where volume requires it.

The fragment does not include raw SQL, bindings or exception context. It also does not count all queries or measure the complete request. Laravel's cumulative query-time monitoring answers a different question from this individual-query threshold.

Step 3: Count repeated work

Observe query count and relationship access in a representative isolated request. Lazy relationship access inside loops or resource serialization can create many queries even when each is individually moderate.

Use eager loading where it preserves the required data and authorization scope. Avoid retrieving every relation and column indiscriminately; reducing query count can still increase memory and transferred data excessively.

Check pagination, aggregates and serialization behavior. A corrected database query can remain part of a slow request if the application then processes an unbounded result set.

Repeated queries, expensive execution plans and lock waits require separate diagnosis.
An index does not fix every connection wait or application loop.

Step 4: Inspect evidence of slow MySQL queries in Laravel safely

Use the slow-query log or Performance Schema through the authorized database owner. Select a bounded time window and protected output because SQL text and parameters can contain sensitive values.

Aggregate summaries can help identify repeated expensive shapes, but verify their reset window, units and instrumentation availability. A cumulative historical total is not the same as the current incident rate.

Do not enable unbounded tracing indefinitely merely because it reveals more detail. Collection can add disk and processing cost during an already busy period.

Step 5: Review the plan and actual waiting

For a reader's hypothetical schema, ordinary EXPLAIN can describe a representative selection:

SQL
EXPLAIN
SELECT id, created_at
FROM orders
WHERE tenant_id = 42 AND status = 'pending'
ORDER BY created_at DESC
LIMIT 20;

The table and values are illustrative. Review the plan against the actual schema, predicates and data distribution; no specific index or execution time is claimed by this example.

EXPLAIN ANALYZE actually executes supported statements. Use it only with a reviewed operation and suitable isolated or authorized target; do not treat its name as a guarantee of zero workload impact.

Inspect lock and transaction evidence separately. A sensible plan can still wait behind a long-running transaction. Adding another index will not remove every coordination problem.

Step 6: Choose and compare one correction

Candidate corrections include reducing repeated work, narrowing returned columns, aligning an index with the measured query or shortening an inappropriate transaction. Review write and storage consequences of new indexes.

Acceptance area Required comparison
Request latency Same workflow and representative conditions
Query behavior Count, timing and waiting evidence
Correctness Same authorized records and ordering
Resource cost Memory, write overhead and storage impact
Failure behavior Timeouts and bounded error handling remain valid

Do not invent before-and-after numbers. Record actual measurements from a controlled exercise, including what differs from production.

Representative data and a single reviewed correction support performance and correctness comparison.
Never remove tenant or authorization filters to improve a benchmark.

Step 7: Verify release and recurrence

Roll out the correction through the existing release and migration owners. Observe the affected workflow over the defined interval and retain its release reference with the comparison evidence.

Our Laravel production checklist covers deployment gates. Add a bounded regression observation for the expensive workflow rather than leaving raw-query logging enabled indefinitely.

For evidence-led database optimization fitted to your Laravel application, discuss the project with Cloudsoft Zone.

Featured image: Cloudsoft Zone technical layout with mysql artwork by Oracle Corporation; vectorized by VulcanSphere (Public domain (text logo); trademark retained). Product mark resized proportionally for identification; no endorsement implied. Layout: CC BY-SA 4.0.

Frequently asked questions

  • Does a fast-looking EXPLAIN estimate prove a query is fast?

    No. Estimates are planning evidence. Compare them with representative execution and lock or workload observations; EXPLAIN ANALYZE actually executes the supported statement.

  • Can many short queries make a Laravel request slow?

    Yes. Repeated relationship queries or other unnecessary work can consume the request budget even if no individual query crosses a slow threshold.

  • Should I log every SQL statement and binding in production?

    Do not do that casually. Queries and bindings can expose customer data and high-volume collection has costs. Use bounded safe timing and protected diagnostic sampling.

Sources

  1. Laravel query events and cumulative monitoring — Laravel
  2. Eloquent relationship loading — Laravel
  3. MySQL EXPLAIN semantics — MySQL
  4. MySQL slow-query log behavior — MySQL
  5. Performance Schema statement summaries — MySQL

New tools, once a week

One short email listing what joined the directory.

The weekly email about new tools and occasional newsletters. Unsubscribe at any time.

Comments

No comments yet. Be the first to join the conversation.

Leave a comment

Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.

Never published. Used only to contact you about this comment.

Loading the security check…

Comments are moderated before publication.