In this episode, we turn our attention to eager loading with Laravel, specifically focusing on comments that have relationships with users. We start by setting up our data—adding a new user manually in the database and assigning some comments to this new account, just to get a bit more variety in our sample data.
From there, we install the Laravel Debugbar so we can keep an eye on how many database queries are being executed. Right away, we see that there are way more queries happening than necessary—clearly that N+1 problem when accessing users for every comment.
To fix this, we dive into our Livewire comments component and add eager loading for the user relationship. We see our query count drop, but we notice another layer for child comments is still causing extra queries. By eager loading the user relation for the child comments as well, we're able to bring the query count down even further.
We also tackle the nesting issue, making sure we only pull two levels of comments to keep things efficient and readable. After adjusting our loop and checks, the query count drops even more.
Lastly, we explore how to not only eager load relationships but also order them as needed. Using a closure in our eager loading, we show how you can customize the ordering of child comments—making them appear oldest or newest at the top, depending on your preference. The episode shows the practical value and flexibility of eager loading relationships in Laravel, keeping your app fast while giving you full control over how related data is loaded and displayed.