๐ฆ๐๐ผ๐ฝ ๐ฆ๐น๐ผ๐ ๐๐ฎ๐ฟ๐ฎ๐๐ฒ๐น ๐๐ฝ๐ฝ๐
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.
- One for all posts.
- One for all related users. It links the users to posts in memory. Your app stays fast regardless of data size.
Additional options:
- Load many relations: with(['user', 'comments'])
- Load nested relations: with('user.profile')
Your app runs faster. Your server load drops. Use this method whenever you use loops with relations.