Struggling with slow performance in your Laravel application? You’re not alone.
One of the most common causes of sluggish apps is slow database queries — and identifying them early can save you hours of debugging, user complaints, and lost traffic. Fortunately, Laravel makes it easy to log slow queries with just a few lines of code.
In this post, I’ll walk you through a step-by-step approach to detect and log slow queries in Laravel — even if you’re just practicing on dummy data.
Slow Database Queries Laravel: Find Them Fast
Before diving into code, let’s understand why this matters:
- 🐢 Slow queries slow down your entire application
- 🧩 They can indicate missing indexes, poor query structure, or unnecessary joins
- 💰 In a live app, they can cost you users — and revenue
Being able to track and log these queries is a powerful way to take control of performance.
🛠️ Step 1: Enable Query Logging in Laravel
In AppServiceProvider.php, add the following to the boot() method:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
public function boot()
{
DB::enableQueryLog();
DB::whenQueryingForLongerThan(1000, function ($connection) {
Log::warning('⚠️ Long running queries detected:', $connection->getQueryLog());
});
}
🕐 This logs any query that takes longer than 1000ms (1 second).
You can adjust the threshold as needed — even down to 50ms for dev environments.
🧪 Step 2: Create Dummy Data for Testing
Use a seeder to simulate a real-world dataset:
php artisan make:seeder PostSeeder
In PostSeeder.php:
use App\Models\Post;
public function run()
{
Post::factory()->count(10000)->create();
}
Run the seeder:
php artisan db:seed --class=PostSeeder
Now your database has enough records to test heavy queries.
⚡ Step 3: Trigger a Slow Query (For Testing)
You can simulate a slow query using a simple route:
use Illuminate\Support\Facades\DB;
Route::get('/slow-query', function () {
usleep(2000000); // 2 seconds delay (in microseconds)
return DB::table('posts')->limit(1000)->get();
});
Or if you’re using MySQL, try:
return DB::select('SELECT SLEEP(2), title FROM posts LIMIT 1');
This will create a delay long enough to trigger the logging.
📂 Step 4: Check the Logs
Open this file:
storage/logs/laravel.log
And you’ll see something like:
[2025-04-04 14:15:22] local.WARNING: ⚠️ Long running queries detected: [...]
Boom! You’ve just caught a slow query.
🔐 Bonus: Log Full SQL with Bindings
Want to see exact SQL statements?
DB::listen(function ($query) {
Log::info("SQL: {$query->sql} | Time: {$query->time}ms", $query->bindings);
});
Add this to your AppServiceProvider@boot() during development.
🧩 Real-World Use Cases
- Monitoring API endpoints that return too slowly
- Debugging admin dashboards with large datasets
- Detecting missing indexes on frequently-used tables
✅ Wrap-Up
Laravel gives you the tools — you just need to flip the switch.
By logging long-running queries:
- You gain better visibility over your app’s performance
- You prevent performance bottlenecks early
- You build more efficient, scalable applications
🔔 Next step: Try this on your current project and keep the logs running while developing. You’ll be amazed how quickly you spot patterns.
What Counts as Slow, and Who Decides
A hundred milliseconds is a reasonable default threshold, but the right number is contextual: an admin report can afford a second, a checkout path can't afford fifty milliseconds. Set the listener threshold per environment — aggressive in staging so problems surface early, and slightly relaxed in production so the log stays readable. The point of logging queries isn't collecting them; it's making the log short enough that a human actually reads it. A slow-query log with ten entries per day gets fixed; one with ten thousand gets ignored.
Reading a Slow Query Like a Story
Each logged entry answers three questions: what ran, how long it took, and where it came from. The usual suspects rank predictably — missing indexes on foreign keys and where-clause columns first, N+1 patterns disguised as many fast queries second, and unbounded result sets third. For anything mysterious, paste the SQL into EXPLAIN and look for full table scans. And watch for the sneaky category: queries that are individually fine but run on every request — a settings lookup or session write that belongs in cache. Frequency times cost is the real metric, and the log gives you both once you start reading it that way.
Closing the Loop in Production
In production, pair the listener with log rotation and ship entries somewhere visible — a Slack channel for anything over half a second works remarkably well as social pressure. Review the log as part of release ritual: a deploy that introduces a new slow query should be caught the same week, not discovered in a quarterly panic. Teams that treat the slow-query log as a running conversation about performance keep response times flat as the product grows; teams that treat it as forensics only open it during outages, which is exactly the most expensive time to learn.
The One-Line Threshold Debate
Teams argue about the right threshold; the winning move is starting strict and loosening with evidence. Begin at fifty milliseconds in staging — you'll be shocked what surfaces — then raise it only when everything logged is genuinely acceptable. The threshold isn't a standard to meet; it's a flashlight whose beam you adjust until it points at exactly the queries worth an engineer's hour.
Beyond Logging: The Fix Priority
When the log fills, fix in value order: the query that's slow AND frequent first, the slow-but-rare report last. Multiply duration by daily frequency for a rough cost score — a 200ms query on every page view outranks a 3-second nightly export by orders of magnitude. This one sorting habit keeps optimization effort pointed at user experience instead of at whichever query looks scariest in isolation.
The Payoff, Measured
One client engagement summarizes the value: forty minutes installing this listener, one afternoon fixing what it surfaced, and their p95 response time fell by more than half. No new servers, no caching layer, no rewrite — just visibility applied to queries nobody had ever seen listed. Detection isn't the glamorous half of performance work, but it decides whether the glamorous half aims at anything real.
From Detection to Culture
Catching slow database queries Laravel style works best as a habit, not a hunt — leave the listener on in staging permanently and review the log before every release. My fixing N+1 queries and eager loading done right go deeper.
If you want query monitoring wired into your app, that's something I do through Ramlit.