In this episode, we're tackling the classic N+1 query problem in Laravel by introducing eager loading. We start by identifying where our code is causing multiple unnecessary database queries, especially when loading related data (like fetching users for each post). Then, we implement the simple solution—using the with
method to eager load the user
relationship on our Post
model.
You'll see how this little change drops our query count down dramatically (from multiple to just two!) no matter how many posts or users we add. We demonstrate this by adding extra users and posts, checking the query count with Laravel Debug Bar, and verifying that even with more data, we don't run into more queries.
We also show how to spot duplicated queries using the Debug Bar, so you can quickly see if you have any N+1 issues lurking. The episode wraps up by emphasizing that this basic form of eager loading will vastly improve your application's performance, and gives a teaser that we'll dive into more advanced scenarios (like nested relationships) later in the course.