logo

Let Eloquent eager load relationships for you

And how it differs from chaperone

Joel Clermont
Joel Clermont
2026-10-27

In an earlier tip, I showed how chaperone() stops Eloquent from querying for a parent it already loaded. Laravel also has a broader feature that tackles N+1 problems in a different way.

// in AppServiceProvider::boot()
Model::automaticallyEagerLoadRelationships();

With this enabled, accessing an unloaded relationship on one model loads it for every model in the same collection, in a single query.

$posts = Post::all();

foreach ($posts as $post) {
    foreach ($post->comments as $comment) {
        echo $comment->post->title;
    }
}

There's no with() and no chaperone() here. The first time you touch $post->comments, Laravel loads the comments for all the posts. And the first time you touch $comment->post, it loads the posts for all the comments.

With 3 posts and 12 comments, that's 3 queries instead of 16.

Also, if you don't want this behavior everywhere, you can turn it on for a single collection.

$posts = Post::all()->withRelationshipAutoloading();

So how is this different from chaperone()?

Look at that third query. Automatic eager loading still goes back to the database for the posts, even though we already had them. And the post it hands you is a separate copy, not the same instance from the outer loop. Change a value on $comment->post, and $post won't see it.

chaperone() skips that query and gives you the exact same instance. The two also work together. Turn on automatic eager loading and add chaperone() to the relationship, and the loop drops to 2 queries.

One more thing to know before you turn this on globally. The Laravel docs still mark automatic eager loading as beta, and say its behavior may change even in patch releases.

Honestly, I'm not using this yet in my apps, but it's an interesting enough feature that I wanted to make sure you were aware of it.

Here to help,

Joel

P.S. Not sure where the N+1 queries are hiding in your app? Finding them is a regular part of our code review.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice.