Andrew Cavanagh

Developer.  Project Architect.  Huge Nerd.

(not necessarily in that order)

There was a great article in Laravel News recently about eager loading and how to use it for efficient queries. I’m summarizing it here for my own reference.

Basically, if you call a relationship without eager loading it in the initial query, you’re making another query. Say you have a Post model and a Author model with a relationship tying them together, and you do something like:

$posts = App\Post::all();
foreach ($posts as $post) {
    echo $post->author;

If you have 100 posts, you’re making 101 queries - one to get the posts, and one for each post to get the author.

However, if you do this instead:

$posts = App\Post::with('author')->all();
foreach ($posts as $post) {
    echo $post->author;

Then you’re only making two queries, one for all the posts and one for all the authors in those posts.

That’s one of those things that I kinda knew and tried not to abuse but didn’t think that much about until I was profiling a slow page by adding this to the boot() method in AppServiceProvider:

        DB::listen(function($query) {

and then watching all the queries log out when I loaded the page. It was a little embarrassing to see how many places I was calling for a related resource without eager loading the relationship.

comments powered by Disqus