In this episode, we dive into the concept of eager loading, which we've already touched on earlier in the course, but now we're applying it in a real scenario. We start off by pulling in the Laravel Debugbar to help us see what's going on under the hood with our database queries.
We look at how, when you load your courses and start attaching topics to them, each course tries to fetch its related topics, resulting in multiple database queries—hello, N+1 problem! To really show the issue, we attach topics to a couple of courses and even add a third course. Right away, we can see through the debug bar that the number of queries increases with each additional course.
To fix this, we walk through how to eager load related data—specifically, loading all topics for each course in just one extra query, rather than one-per-course. It's super simple thanks to Laravel's with
method: we just add Course::with('topics')
to our data fetch, and boom, the N+1 problem is gone.
After applying eager loading, no matter how many courses or topics you add, the database queries remain minimal—making your app much more efficient. This episode is all about seeing why eager loading matters and how ridiculously easy it is to implement!