Laravel N+1 Query Problem: Find It, Fix It, Prevent It
The Laravel N+1 query problem is the most common reason a page that was fast with ten rows becomes slow with a thousand. It happens when you load a list of models and then touch a relationship on each one inside a loop, so Eloquent runs one query for the list plus one more query per row. In a test with 50 posts, a simple loop that prints each post's author ran 51 queries . The same page with one…
The Laravel N+1 query problem occurs when loading a list of models and accessing their relationships within a loop, causing Eloquent to generate excessive queries. For instance, a simple loop printing each post's author resulted in 51 queries for 50 posts. This inefficiency can be spotted by enabling query logging and checking query counts.
To fix N+1 queries, eager load related models using the with() method, as it instructs Eloquent to run only two queries regardless of the number of posts. Another solution is to use the withCount() method, which allows the database to count relationships without loading them. Loading relations on a pre-existing collection can also help, as in the example of loading authors after fetching a collection of posts.
Laravel 12.x introduces automatic eager loading, which can be enabled in the AppServiceProvider to automatically eager load relationships upon access. Developers can also enforce eager loading in development to prevent N+1 queries, with a warning being thrown if lazy loading is accidentally attempted.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.