Laravel Slow Queries: Fix N+1, Indexes and DB Bottlenecks
Measure cumulative query time, eliminate N+1, inspect real MySQL or MariaDB plans, then test composite indexes before deploying.
Quick answer: To fix slow Laravel database queries, first measure query count and total database time for one representative request. Eliminate Eloquent N+1 queries with explicit eager loading, examine the most expensive SQL with the correct MySQL or MariaDB execution-plan command, and add an index only when it matches the actual filter and sort pattern. Finally, compare results on the same data and workload before deploying. This method is usually safer than increasing VPS RAM or blindly adding database indexes.
Laravel makes it easy to express database access with Eloquent, but a page can become slow when one innocent template creates dozens of relationship queries, when a filter scans a growing table, or when offset pagination skips large numbers of rows. These issues affect PHP/Laravel applications on shared VPS servers as well as larger cloud deployments. This guide explains a repeatable diagnosis process without inventing a universal throughput benchmark.

Why can a Laravel page be slow even when PHP and CPU look fine?
A slow page is not necessarily running one slow SQL statement. For example, a page that loads 40 posts and then fetches each author's name inside a loop may run one query for posts plus 40 queries for authors. Every query could be individually fast, but network round trips, connection contention and repeated work add up. In a different case, a single query may scan hundreds of thousands of rows because the filter and order cannot efficiently use a suitable index.
Separate three measurements before optimizing: query count (how often SQL runs), individual query duration (how expensive one statement is), and cumulative database time (how much of the request is spent querying). Also record the endpoint, number of returned rows, and representative input filters. Averages alone can conceal expensive tail requests.
A useful diagnostic order
First reproduce a slow URL or API request on staging. Next capture the SQL queries and identify duplicates. Then inspect the costly query plan and its indexes. Only after that should you alter Eloquent loading, pagination, SQL predicates, or the schema. A database change without a before-and-after measurement is a guess, not a demonstrated optimization.
Step 1: Measure queries with Laravel's built-in tools
The official Laravel database documentation describes DB::listen() for query events and DB::whenQueryingForLongerThan() for a cumulative threshold. These features address different questions. Use a listener in a restricted test environment to observe individual query durations, and use cumulative monitoring to detect requests that spend too long in the database overall.
Log individual query times safely
The following abbreviated service-provider example records a query's elapsed time and parameterized SQL only in local development. SQL text itself may reveal sensitive table or field names, so avoid sending raw queries or bindings into public logs. Do not enable verbose query logging for every production request without a retention and sampling plan.
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
// In AppServiceProvider::boot()
if (app()->environment('local')) {
DB::listen(function (QueryExecuted $event) {
logger()->debug('SQL query', [
'ms' => $event->time,
'sql' => $event->sql, // Placeholders, not raw bindings
]);
});
}
If a request executes 60 nearly identical author lookups, the pattern is a strong N+1 signal. If a single aggregate query dominates the request, focus on that SQL statement instead. Logging all bindings with interpolated SQL can expose personal data or secrets, so the example deliberately avoids toRawSql() in operational logs.
Understand cumulative database time
DB::whenQueryingForLongerThan(500, ...) is a threshold for total query time during a request, not proof that any individual SQL statement took 500 milliseconds. That distinction matters: 100 queries at a few milliseconds each can cross the threshold even when none is slow alone. The callback can trigger an internal alert, metric, or sampled log message.
use Illuminate\Database\Connection;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
// In a service provider's boot() method
DB::whenQueryingForLongerThan(500, function (
Connection $connection,
QueryExecuted $event
) {
logger()->warning('High cumulative DB time', [
'connection' => $connection->getName(),
'last_query_ms' => $event->time,
]);
});
Choose 500 ms only as an illustrative starting point; the right budget depends on your endpoint and service-level objectives. Confirm that alert callbacks, request logging and framework versions work as intended before enabling them on a busy site.
Step 2: Fix the Eloquent N+1 query problem
The Laravel Eloquent relationships guide explains that accessing a relationship property can lazy-load it. Doing that for each model in a collection is the classic N+1 issue. A common fix is to load the related models up front with with(). This changes the query pattern without requiring a schema migration.
Before: a relationship query inside every loop
// Illustrative model names; adapt to your schema.
$posts = Post::query()->latest('id')->limit(25)->get();
foreach ($posts as $post) {
echo $post->author->name; // May lazy-load each author
}
When the author relationship has not been loaded, this can issue one query for posts and additional author lookups. The exact query count depends on your data, relationship configuration and any eager-loading defaults; do not treat a fixed count as a benchmark.
After: eager load the relationships you actually display
$posts = Post::query()
->with('author')
->latest('id')
->limit(25)
->get();
foreach ($posts as $post) {
echo $post->author?->name;
}
Eager loading can reduce repeated lookups into a smaller number of queries. However, loading every relationship on every endpoint can waste memory and bandwidth. Select only the relationships required by a specific page and paginate large collections rather than calling all() for thousands of models.
Use withCount instead of loading every comment
If the interface only needs a count, it usually does not need the related models. For a post list displaying comment totals, Laravel's withCount('comments') can provide the aggregate without hydrating an entire comment collection:
$posts = Post::query()
->with('author')
->withCount('comments')
->orderByDesc('id')
->paginate(25);
// In a view: $post->comments_count
Use query monitoring to check the generated plan, especially when relationships or filters grow complex. One aggregate query is not automatically cheap; indexes still matter.
Catch accidental lazy loading during development
Laravel supports Model::preventLazyLoading(). Enabling it in development or tests can reveal relationship access that would otherwise silently issue queries. Restrict it to appropriate environments to avoid unexpectedly breaking public traffic while introducing the rule.
use Illuminate\Database\Eloquent\Model;
// In AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());
This helps prevent regressions, but it is not a substitute for performance tests. Eager loading a huge graph can still create a slow or memory-heavy request.
Step 3: Use the correct EXPLAIN command for your database
MySQL and MariaDB share familiar SQL syntax, but their runtime plan-inspection commands are not interchangeable. MySQL 8.4: use EXPLAIN ANALYZE SELECT ... to inspect actual execution. MariaDB: use ANALYZE SELECT ... or ANALYZE FORMAT=JSON SELECT .... Plain EXPLAIN SELECT ... is an additional starting point for both products. Verify the engine and version before copying commands between servers.
MySQL 8.4 example
EXPLAIN ANALYZE
SELECT id, tenant_id, status, created_at
FROM orders
WHERE tenant_id = 42 AND status = 'paid'
ORDER BY created_at DESC, id DESC
LIMIT 25;
MySQL's official EXPLAIN manual documents plan output, including estimated and observed execution information. Look at the access path, loops and number of rows examined. The optimizer may choose a table scan for small or low-selectivity datasets; a scan is not automatically a bug.
MariaDB example
ANALYZE FORMAT=JSON
SELECT id, tenant_id, status, created_at
FROM orders
WHERE tenant_id = 42 AND status = 'paid'
ORDER BY created_at DESC, id DESC
LIMIT 25;
The MariaDB ANALYZE documentation explains how this command combines plan information with execution statistics. On a production database, start with normal EXPLAIN and review whether executing the target statement is safe. Runtime plan-analysis commands actually execute their query; run expensive statements on staging or a controlled read-only replica.
Important: avoid blindly applying runtime plan commands to writes or locking statements. The examples here use SELECT and should be adapted to your environment, permissions and data sensitivity.
Step 4: Design composite indexes around the real query
An index should support your most frequent filtering, joining or ordering patterns. For the sample query above, a candidate composite index is (tenant_id, status, created_at, id). Its equality-filtered columns come first, followed by the sorting keys. This is a hypothesis to test with actual plans and data distributions, not a universally optimal index.
MySQL documents the leftmost-prefix property of multi-column indexes. An index on four columns can support lookups using its first column or successive leading columns; it does not guarantee an efficient lookup when a query filters only by a later column. Whether the engine can satisfy a DESC sort also depends on the index definition and query shape.
Laravel migration example
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('orders', function (Blueprint $table) {
$table->index(
['tenant_id', 'status', 'created_at', 'id'],
'orders_tenant_status_created_id_idx'
);
});
Before creating this index, inspect existing keys, write volume and table size. Each extra index consumes storage and adds overhead to inserts and updates. Depending on the database engine and table, building an index can affect locking and replication. Test the migration on staging, plan a maintenance window if needed, and prepare a rollback. Do not create duplicate or overlapping indexes without measuring the trade-off.
Why adding an index can fail to improve the query
Common causes include poor selectivity, a filter that cannot use the index's leading columns, expressions applied to indexed columns, incompatible data types, stale statistics or an ORDER BY that needs a separate sort. Read the plan rather than assuming the index name alone proves it is used. A well-designed query with an ineffective index can still be slower than expected.
Step 5: Choose pagination deliberately
Offset pagination is convenient and supports numbered pages, but high offsets can require scanning or skipping many rows. Laravel's pagination documentation explains that cursor pagination uses ordered-column comparisons and can be more efficient for appropriate large datasets.
Offset pagination for normal admin interfaces
$orders = Order::query()
->where('tenant_id', $tenantId)
->orderByDesc('id')
->paginate(25);
Use this when numbered pages, total counts, or familiar navigation are important and the dataset is manageable. Check query plans and count-query costs before blaming offset pagination for every slow list page.
Cursor pagination for deep, continuously growing feeds
$orders = Order::query()
->where('tenant_id', $tenantId)
->orderByDesc('id')
->cursorPaginate(25);
A unique, indexed ordering key is helpful here. Cursor pagination does not offer the same arbitrary page-number behavior as offset pagination. If ordering by a non-unique timestamp, include a deterministic tie-breaker and confirm indexes support the chosen order.
What else causes slow queries on a small VPS?
Not every database bottleneck is an Eloquent mistake. A queue-worker burst may contend with public requests for the same database connections. A slow transaction may hold locks; a report may sort a large intermediate result; a frequently executed count query may grow more expensive over time. Check connection count, disk activity and lock waits before adjusting PHP-FPM or database memory settings.
Laravel also documents php artisan db:monitor --databases=mysql --max=100 to emit an event when configured connection thresholds are exceeded. The number 100 is an example, not a recommended threshold for every VPS. Monitoring open connections complements query profiling; it does not identify the SQL responsible for every latency spike.
When background jobs cause load, start by limiting concurrent workers and checking retry behavior. A task with duplicate processing can increase database writes unexpectedly; Rubic8's Laravel webhook idempotency guide shows why retry-safe workflows matter. If an application also makes external API calls, apply separate HTTP timeout and destination controls as explained in the Laravel SSRF prevention guide.
A safe before-and-after test plan
Use a staging dataset close to production scale and realistic filters. Record query count, cumulative SQL time, p50 and p95 request latency, number of examined rows, and memory use before changes. Apply one optimization at a time: eager loading, an index, a modified predicate, or a pagination strategy. Then repeat under similar conditions. If a change improves one endpoint but worsens database writes or worker contention, include that trade-off in the decision.
Environment changes should be separated from SQL changes. Upgrading PHP or framework versions does not automatically fix an N+1 query, and it can complicate diagnosis if performed in the same release. Rubic8's PHP 8.6 compatibility and Laravel staging guide recommends treating runtime upgrades as a separately verified change.
For an AI-backed SaaS app, watch the database impact of agent state, vector-search metadata, queue retries and tool-call logging. The agent API and asynchronous tool-calling guide discusses durable state and queue deadlines; those architectural patterns should be evaluated with the same query-budget discipline.

FAQ: Laravel slow database queries
How do I find slow queries in Laravel without installing a package?
Use DB::listen() to observe query events in a restricted development environment and DB::whenQueryingForLongerThan() to detect excessive cumulative database time. Then run EXPLAIN for representative SQL and confirm the result with your database's runtime plan tool when safe.
Does eager loading always make Laravel faster?
No. Eager loading commonly fixes repeated N+1 relationship lookups, but loading large, unnecessary relationships can increase memory and transfer costs. Measure both query count and total work.
Should I use EXPLAIN ANALYZE on MariaDB?
Use MariaDB's documented ANALYZE SELECT or ANALYZE FORMAT=JSON SELECT syntax. EXPLAIN ANALYZE is the familiar MySQL form. Check your engine version rather than assuming commands are identical.
Is adding more database indexes always better?
No. Every index has storage and write costs, and the optimizer may ignore an unsuitable index. Create indexes to match real predicates and sort patterns, then verify plans and performance before deployment.
When is cursor pagination a good choice?
Cursor pagination is often useful for large, sequentially browsed feeds with stable, indexed ordering. Offset pagination remains useful when visitors need numbered page navigation or arbitrary page jumps.
Can changing VPS RAM fix N+1 queries?
More memory may reduce some resource pressure but does not remove unnecessary relationship queries. Eliminate repeated SQL and inefficient scans first, then measure whether the remaining workload is resource-bound.
Sources and methodology
This guide relies on the official Laravel Database, Eloquent Relationships and Pagination documentation, the MySQL 8.4 EXPLAIN manual, the MySQL multi-column index guide, and the MariaDB ANALYZE reference. Code is illustrative, not a benchmark from Rubic8 production. Confirm APIs against the Laravel release and database engine actually deployed in your application. Last editorial review: November 24, 2026.
Rubic8 Editorial Team
Editorial Team
Rubic8 creates practical guides and free tools for developers, webmasters, and digital publishers. Our fast-changing technical content is reviewed against current primary documentation before publication.