
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.

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:
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.

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:
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.

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
- Laravel query events and cumulative monitoring — Laravel
- Eloquent relationship loading — Laravel
- MySQL EXPLAIN semantics — MySQL
- MySQL slow-query log behavior — MySQL
- Performance Schema statement summaries — MySQL
Read next

TutorialDevOps5 min read
MySQL production configuration for Laravel applications: a safe operating baseline
Review MySQL production configuration for Laravel using measured memory and connection budgets, explicit durability, protected access and verified restore procedures.
New tools, once a week
One short email listing what joined the directory.
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.
More from Cloudsoft Zone

TutorialDevOps5 min read
Expand and contract database migrations: safe deployment with live writers
Use expand and contract migrations to keep old and new application versions compatible while backfilling retained data and verifying every writer before schema contraction.
By Nilesh Kushvaha

TutorialDevOps5 min read
Database backup restore tests: prove recovery before an outage
Run database backup restore tests on an isolated target with artifact checks, schema and business invariants, disabled external side effects and a measured recovery timeline.
By Nilesh Kushvaha

Resource guideDevOps4 min read
MySQL backup strategies: full, incremental and point-in-time recovery chains
Compare MySQL backup strategies by the complete recovery chain: consistent base backups, incremental history, retained binary logs, compatible tooling and verified restoration.
By Nilesh Kushvaha