Coding

Optimising Laravel Queries: Don’t Let Your Database Call You Lazy

In this blog, we will explore strategies for identifying slow queries and resolving performance issues while maintaining Laravel's simplicity.

Dec 10, 2025 7 min read

If your Laravel application feels slow or unresponsive, it's easy to blame the server or the database. However, the real issue often lies in how your queries are constructed. Inefficient database calls can significantly affect speed and performance, even when using Laravel's elegant syntax.

Laravel's Eloquent ORM prioritises simplicity and readability. Each interaction with a model can trigger multiple queries, and as your database expands, small inefficiencies can accumulate. This can result in longer load times and a poor user experience.

The good news is that you don't have to abandon Eloquent or completely rewrite your application. By employing the right techniques, you can make your queries faster, smarter, and more efficient. 

Optimising queries is just one part of writing efficient and maintainable code. To understand why performance-focused coding matters, read our blog Why Writing Optimized Code Is Important

In this blog, we will explore strategies for identifying slow queries and resolving performance issues while maintaining Laravel's simplicity.

1. Your Database Isn’t the Problem; Your Queries Might Be

Imagine you’re loading a list of users along with their posts. You run a simple Eloquent call:

$users = User::all();
foreach ($users as $user) 
  {
    echo $user->posts->count();
  }

It appears harmless, but this triggers multiple queries, one for each user, resulting in the N+1 query problem. As your data grows, performance drops drastically.

Optimising queries isn’t about writing less code. 

It’s about writing smarter code that minimises load times, scales efficiently, and provides a faster experience for users.

Before optimisation, each user triggers a separate query. After optimisation, a single well-structured query retrieves all the data at once, drastically improving response time.

2. Understanding How Laravel Handles Queries

Laravel’s Eloquent ORM makes database interactions effortless. You work with models and relationships, and Laravel automatically translates them into SQL commands behind the scenes.

For example:

$users = User::where('active', true)->get();

Eloquent converts this into a SQL query automatically.

Eloquent vs. Query Builder

  • Eloquent ORM: Expressive and simple & ideal for most use cases.
  • Query Builder: Closer to raw SQL, offering more control and better performance for complex operations.

Think of it as a balance: use Eloquent for readability and Query Builder (or raw SQL) for performance-critical logic.

3. Common Performance Killers in Laravel Queries

Even experienced developers sometimes make small mistakes that lead to significant performance issues.

Here are a few common pitfalls to avoid:

  • The N+1 Problem: When relationships aren’t eager-loaded, each model fetch triggers an extra query. Fix:
 $users = User::with('posts')->get();
  • Fetching Unnecessary Data: Using Model::all() retrieves every column and record. Fix:
$users = User::select('id', 'name')->get();
  • Queries Inside Loops: Running queries inside loops causes unnecessary repetition. Fetch all data at once or use joins instead.
  • Missing Indexes: Without proper database indexing, queries perform full table scans, which drastically reduce performance.

When optimised properly, queries execute in a fraction of the time and with fewer database calls, resulting in a faster and more efficient application.

4. Optimising Queries Like a Pro

Once you identify inefficiencies, a few simple changes can dramatically improve your application’s performance.

1. Use Eager Loading

Fetch related models in a single query instead of separate ones:

$users = User::with('posts', 'comments')->get();

2. Select Only What You Need

Load only the required columns to reduce unnecessary data:

$users = User::select('id', 'name')->with('posts:id,user_id,title')->get();

3. Use Chunking for Large Datasets

Handle large data efficiently by processing it in chunks:

User::chunk(200, function ($users) {
    // Process each batch
});

4. Cache Repetitive Queries

Use Laravel’s cache for data that doesn’t change often:

$users = Cache::remember('users', 3600, fn() => User::all());

5. Optimise Database Indexes

Add indexes to columns that are frequently searched or filtered:

CREATE INDEX users_email_index ON users (email);

6. Avoid Query-in-Loop

Replace repetitive queries inside loops with batch operations or joins.

When these techniques are applied, queries execute faster, CPU usage drops, and pages load more smoothly. Consistently writing well-structured, efficient code is just as critical as optimising queries. Discover why it’s key to performance in our blog Why Writing Optimized Code Is Important.

5. Advanced Techniques for Serious Performance Gains

When your app scales, advanced optimisation techniques help maintain performance effectively.

  • Use the EXPLAIN command in MySQL: It shows how queries are executed and where indexes or joins might be slowing things down.
  • Aggregate Smartly: Use functions like loadCount() or loadSum() instead of counting relationships manually.
  • Leverage Redis Caching: Cache frequently used results to avoid unnecessary database hits.
  • Offload Heavy Tasks: Use queues to process time-consuming operations asynchronously.

For example:

$users = User::withCount('posts')->get();

This single query fetches both users and post counts efficiently in one operation.

6. When to Use Raw Queries or Query Builder Instead

Eloquent is clean and readable, but adds a bit of overhead. For complex joins, analytics, or massive data sets, using Query Builder or raw SQL often performs better.

$results = DB::select('SELECT name, COUNT(*) as post_count FROM posts GROUP BY name');

Eloquent is perfect for everyday operations. For high-performance scenarios, raw queries provide better control and speed.

While raw queries can boost performance, they must be handled securely to avoid vulnerabilities. Learn how Laravel protects your app with built-in security layers like CSRF in our post CSRF Tokens: Your App’s Bodyguards.

An Eloquent query might take around 300 milliseconds to execute, while the same query written in raw SQL could complete in roughly 120 milliseconds.

The goal is not to abandon Eloquent but to understand when direct SQL can deliver better speed, especially for data-heavy operations.

7. Testing and Monitoring Query Performance

Optimisation is a continuous process. Laravel provides several tools to monitor and analyse query performance:

  • Laravel Debugbar: Displays all executed queries and their timings during development.
  • Laravel Telescope: Offers a detailed view of queries, exceptions, and request performance.
  • Performance Profilers: Tools such as Blackfire and New Relic help you identify slow database calls and measure improvements over time.

You can also log queries manually to inspect them:

DB::enableQueryLog();
Log::info(DB::getQueryLog());

By tracking your queries, you can detect slowdowns early and keep your app running efficiently.

Practical Case Study: From Slow to Swift

Before optimisation:

$users = User::all();
foreach ($users as $user) {
    echo $user->posts->count();
}

After optimisation:

$users = User::withCount('posts')->get();
foreach ($users as $user) {
    echo $user->posts_count;
}

This small change reduced the number of queries from 101 to just 1, cutting response time by nearly 85%.

The optimised version executes almost instantly compared to the lag of the original approach, proving that small adjustments can have a massive impact.

Best Practices and Takeaways

Here’s your quick Laravel optimisation checklist:

  • Use eager loading wisely
  • Fetch only necessary columns
  • Process large data in chunks
  • Cache frequent queries
  • Add indexes on key columns
  • Avoid queries inside loops
  • Monitor performance regularly

Building scalable applications is not about writing more code. It’s about writing efficient, optimised queries that respect both your database and your users.

Conclusion

The goal is always to: Code Smart, Query Smarter.

Laravel makes database interactions simple, but simplicity should never come at the cost of efficiency. A well-written query can save seconds of execution time, reduce server load, and drastically improve user experience. 

On the other hand, a single unoptimized query can slow down an entire application, frustrate users, and increase infrastructure costs.

Query optimisation is not just about improving speed; it’s about writing code that scales, lasts, and performs reliably under real-world conditions. Great developers don’t just make things work; they make them work efficiently.

The next time your application feels sluggish, you can just ignore the urge to blame the server or database. Instead, open your query logs, review your relationships, and start refining how your data is fetched. Most performance issues begin and end with how we communicate with the database.

Performance is just one part of building a reliable Laravel app; security is the other. Explore how to strengthen both in our detailed post Why Securing Your App in Laravel Is Easy.

By mastering Laravel’s query optimisation techniques, from eager loading and caching to indexing and raw SQL tuning. You are not only making your code faster but also future-proofing your application for growth.

So, write code that performs as beautifully as it reads. Start optimising today, and let your database call you efficient, reliable, and ready for scale, not lazy.