Have you ever noticed your app getting slower as your database grows, even with just a few users? You might be suffering from the dreaded N+1 query problem without even knowing it.
This performance trap happens silently behind the scenes in many web applications. Luckily, it is easy to spot and fix once you know what to look for.
- What an N+1 query actually is and why it happens.
- How to use Laravel's built-in tools to detect extra database queries.
- How to fix the issue using eager loading.
- How your Laravel backend data flows safely into your Inertia.js and React frontend.
What is the N+1 Query Problem?
An N+1 query happens when your code runs one initial query to fetch a list of items, and then runs N additional queries to fetch related data for each item. If you have 100 users, your app might run 101 separate database queries just to render a simple list. This destroys your application performance and overloads your database.
Imagine you want to display a list of blog posts and their authors in a React component via Inertia.js. In your Laravel controller, you might write code that looks like this.
public function index() {
$posts = Post::all();
return Inertia::render('Posts/Index', [
'posts' => $posts
]);
}The code above fetches all posts, but it does not fetch the author data until the view asks for it. When React tries to render the author name for each post, Laravel secretly triggers a brand new database query behind the scenes.
How to Fix It With Eager Loading
To fix this problem, you need to tell Laravel to load the related data upfront in a single efficient query. This technique is called eager loading. We use the 'with' method in Eloquent to grab everything we need at once.
Here is how you update your Laravel controller to stop making extra queries.
public function index() {
$posts = Post::with('author')->get();
return Inertia::render('Posts/Index', [
'posts' => $posts
]);
}By adding 'with('author')', Laravel reduces your database trip down to just two smart queries total, no matter how many posts you have.
Things to watch out for
A common mistake is forgetting that eager loading only solves the problem for relationships loaded directly in your controller. If your React components pass data back to deeply nested child components that trigger lazy-loaded properties, the N+1 problem can creep back in. Always check your browser network tab or use a database query counter like Laravel Debugbar to verify your query counts.
Open up your current Laravel project right now and install Laravel Debugbar to check your home page query count. Try applying eager loading to your main dashboard route today.