Enhanced Model Relationship Autoloading in Laravel

Need to prevent N+1 queries on single models? Laravel's enhanced relationship autoloading now works directly on individual models, not just collections.
Previously, automatic relationship loading was only available on collections, requiring you to enable it separately for each relationship. Laravel now extends this functionality to individual models, providing more granular control over eager loading optimization.
Let's see how it works:
// Before
$post->tags->withRelationshipAutoloading();
$post->authors->withRelationshipAutoloading();
// After
$post->withRelationshipAutoloading();
// Also works on collections
$users = User::where('vip', true)->get();
return $users->withRelationshipAutoloading();
Real-World Example
Here's how you might use this in a content management system:
class PostController extends Controller
{
public function show(Post $post)
{
// Enable autoloading for the entire model
$post->withRelationshipAutoloading();
// Now all relationship access will auto-eager load
$view = view('posts.show', compact('post'));
// These won't cause N+1 queries
if ($post->tags->isNotEmpty()) {
$view->with('relatedPosts',
$this->findRelatedPosts($post->tags)
);
}
return $view;
}
public function showWithComments(Post $post)
{
// Selective autoloading for specific scenarios
$post->withRelationshipAutoloading();
return [
'post' => $post,
'comments' => $post->comments, // Auto-eager loaded
'author' => $post->author, // Auto-eager loaded
'tags' => $post->tags // Auto-eager loaded
];
}
}
This enhancement provides more flexible control over relationship loading, letting you optimize performance at the model level rather than managing each relationship separately. It's particularly useful when working with individual models in views or API responses.
Stay Updated with More Laravel Tips
Enjoyed this article? There's plenty more where that came from! Subscribe to our channels to stay updated with the latest Laravel tips, tricks, and best practices:
- Follow us on Twitter @harrisrafto
- Join us on Bluesky @harrisrafto.eu
- Subscribe to our YouTube channel harrisrafto