๐—ฆ๐˜๐—ผ๐—ฝ ๐—ฆ๐—น๐—ผ๐˜„ ๐—Ÿ๐—ฎ๐—ฟ๐—ฎ๐˜ƒ๐—ฒ๐—น ๐—”๐—ฝ๐—ฝ๐˜€

Slow apps frustrate users. The N+1 query problem slows your Laravel site. This happens when you load related data inside a loop.

The Problem: You fetch posts. You then fetch the author for each post. If you have 100 posts, you make 101 queries. This kills your database speed.

The Solution: Use Eager Loading. Use the with() method.

Change your code from: Post::all() To: Post::with('user')->get()

How it works: Laravel now makes only 2 queries.

Additional options:

Your app runs faster. Your server load drops. Use this method whenever you use loops with relations.

Source: https://dev.to/prabashanadev/optimizing-laravel-performance-conquering-the-n1-query-problem-with-eager-loading-22in