Skip to main content
📝 Laravel Applications

🚀 How to Detect and Log Slow Database Queries in Laravel Like a Pro (With Examples)

Detect and log slow database queries in Laravel like a pro. Query monitoring, threshold alerts, and performance debugging with real examples.

6 min

Read time

1,064

Words

Apr 04, 2025

Published

Engr Mejba Ahmed

Written by

Engr Mejba Ahmed

Share Article

🚀 How to Detect and Log Slow Database Queries in Laravel Like a Pro (With Examples)

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.

Advertisement
Coffee cup

Enjoyed this article?

Your support helps me create more in-depth technical content, open-source tools, and free resources for the developer community.

Related Topics

Engr Mejba Ahmed

About the Author

Engr Mejba Ahmed

Engr. Mejba Ahmed builds AI-powered applications and secure cloud systems for businesses worldwide. With 10+ years shipping production software in Laravel, Python, and AWS, he's helped companies automate workflows, reduce infrastructure costs, and scale without security headaches. He writes about practical AI integration, cloud architecture, and developer productivity.

Discussion

Comments

0

No comments yet

Be the first to share your thoughts

Leave a Comment

Your email won't be published

2  x  8  =  ?

Continue Learning

Related Articles

Browse All

Comments

Leave a Comment

Comments are moderated before appearing.

Learning Resources

Expand Your Knowledge

Accelerate your growth with structured courses, verified certificates, interactive flashcards, and production-ready AI agent skills.

Sample Certificate of Completion

Sample certificate — complete any course to earn yours

Engr Mejba Ahmed

Engr Mejba Ahmed

Claude Code Expert · Online

👋

Hey there!

Quick Actions

WhatsApp Instant reply

Chat on WhatsApp

+880 1723 741224 · Instant reply

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

[email protected]

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support