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.
In this blog, we will explore strategies for identifying slow queries and resolving performance issues while maintaining Laravel's simplicity.
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.

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.

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.
Think of it as a balance: use Eloquent for readability and Query Builder (or raw SQL) for performance-critical logic.

Even experienced developers sometimes make small mistakes that lead to significant performance issues.
Here are a few common pitfalls to avoid:
$users = User::with('posts')->get();$users = User::select('id', 'name')->get();When optimised properly, queries execute in a fraction of the time and with fewer database calls, resulting in a faster and more efficient application.

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

Fetch related models in a single query instead of separate ones:
$users = User::with('posts', 'comments')->get();
Load only the required columns to reduce unnecessary data:
$users = User::select('id', 'name')->with('posts:id,user_id,title')->get();
Handle large data efficiently by processing it in chunks:
User::chunk(200, function ($users) {
// Process each batch
});
Use Laravel’s cache for data that doesn’t change often:
$users = Cache::remember('users', 3600, fn() => User::all());
Add indexes to columns that are frequently searched or filtered:
CREATE INDEX users_email_index ON users (email);
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.

When your app scales, advanced optimisation techniques help maintain performance effectively.
For example:
$users = User::withCount('posts')->get();This single query fetches both users and post counts efficiently in one operation.

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.

Optimisation is a continuous process. Laravel provides several tools to monitor and analyse query performance:
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.

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.

Here’s your quick Laravel optimisation checklist:
Building scalable applications is not about writing more code. It’s about writing efficient, optimised queries that respect both your database and your users.
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.