Menu

Laravel N+1 Query Problem: How to Find and Fix It
📰

Laravel N+1 Query Problem: How to Find and Fix It

DEV Community: laravel·Aqib Javaid·13 days ago
#CbUOVlwo
#devtolaravel#devto#dev#query#load
Reading 0:00
15s threshold

When a Laravel page that used to load in half a second suddenly takes four, the cause is very often the same: the N+1 query problem . One query fetches a list, and then your code quietly runs one more query for every row. With 10 rows nobody notices. With 500 rows the database is doing 501 round trips for a single page.

This article shows how to find N+1 queries, fix them properly and keep them from returning. It builds on my guide to finding slow queries in Laravel , and if your whole application feels slow, my database optimization and backend performance service is where I start.

What the problem looks like#

Imagine a list of orders that shows each customer's name:

php

Copy

$orders = Order::latest()->take(50)->get();

foreach ($orders as $order) { echo $order->customer->name; // runs a query per order }

Enter fullscreen mode

Exit fullscreen mode

That is 1 query for orders plus 50 for customers: 51 queries . The code looks innocent because relationship access reads like a property.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.