Have you ever opened your browser's network tab and watched a simple page load take three seconds? Often, the culprit is a hidden performance bug called the N+1 query problem, which quietly batters your database with hundreds of unnecessary requests.
You will learn why this problem happens, how to spot it in your own code, and how to fix it using Laravel's built-in tools.
- What an N+1 query actually is under the hood
- How to detect database query floods in Laravel
- How to use eager loading to fix the issue
- Why your frontend Vue app will load data much faster
What is an N+1 Query?
An N+1 query happens when your code runs one main query to fetch a list of items, and then runs N additional queries to fetch related data for each item. Imagine you want to display a list of ten blog posts and their authors on your screen. Instead of asking the database for the posts and authors all at once, your code asks for the posts first, and then makes ten separate trips to the database to ask for each author individually.
This creates eleven total database queries just to render a single page. If you have one hundred posts, you get one hundred and one queries. As your app grows, this small habit will cause your server to grind to a halt.
How to Spot the Problem
In Laravel, you can easily catch these extra queries during local development using a tool like Laravel Debugbar. When you click around your app, the debug bar shows you the exact SQL queries executed on every page request. If you see dozens of identical queries that only differ by an ID number, you have found an N+1 problem.
Fixing It With Eager Loading
The fix is called eager loading, which means telling your database to fetch the main records and their relationships in one single, efficient trip. Instead of letting Laravel fetch relationships lazily when requested, you grab them upfront using the with method.
Here is how you update your Laravel controller to fetch posts and their authors in just two queries instead of dozens:
// Bad: This triggers N+1 queries when looping through posts
$posts = Post::all();
// Good: This uses eager loading to fetch authors in one extra query
$posts = Post::with('author')->get();The key takeaway is that adding that single ->with('author') method reduces your database load from a linear escalation down to a flat two queries, no matter how many posts you have.
Common mistakes
A frequent mistake developers make is forgetting to define the Eloquent relationship properly in the model file before trying to eager load it. Always make sure your Post model has an author() method set up with belongsTo before calling with('author'). Another mistake is using eager loading everywhere 'just in case', which can actually slow down your app if you do not actually need the related data on that specific screen.
Open up an existing Laravel project today, attach a query counter to your API routes, and find one place where you can add an eager load.