0
0
LaravelHow-ToBeginner · 3 min read

How to Eager Load Relationships in Laravel for Faster Queries

In Laravel, you eager load relationships using the with() method on your Eloquent query. This loads related models in the same query, reducing the number of database calls and improving performance.
📐

Syntax

The with() method accepts one or more relationship names as strings. You call it on an Eloquent model query to load related models eagerly.

  • Model::with('relationship')->get(); loads a single relationship.
  • Model::with(['relation1', 'relation2'])->get(); loads multiple relationships.
php
User::with('posts')->get();
💻

Example

This example shows how to eager load the posts relationship on the User model. It fetches all users and their posts in just two queries instead of one query per user.

php
<?php
use App\Models\User;

$users = User::with('posts')->get();

foreach ($users as $user) {
    echo $user->name . " has posts:\n";
    foreach ($user->posts as $post) {
        echo "- " . $post->title . "\n";
    }
}
Output
Alice has posts: - My first post - Laravel tips Bob has posts: - Travel blog - Cooking recipes
⚠️

Common Pitfalls

One common mistake is not eager loading relationships, which causes the N+1 query problem. This happens when Laravel runs one query for the main model and then one query per related model, slowing down your app.

Another mistake is misspelling the relationship name in with(), which results in an error or no data loaded.

php
<?php
// Wrong: causes N+1 queries
$users = User::all();
foreach ($users as $user) {
    echo $user->posts->count(); // runs a query per user
}

// Right: eager loads posts to avoid N+1
$users = User::with('posts')->get();
foreach ($users as $user) {
    echo $user->posts->count();
}
📊

Quick Reference

MethodDescriptionExample
with()Eager load one or more relationshipsUser::with('posts')->get();
withCount()Get count of related modelsUser::withCount('posts')->get();
load()Eager load relationships on existing models$users->load('posts');
loadMissing()Load relationships only if not already loaded$users->loadMissing('posts');

Key Takeaways

Use with() to eager load relationships and reduce database queries.
Eager loading prevents the N+1 query problem by loading related data in fewer queries.
Always check relationship names for typos when using with().
Use withCount() to get counts of related models efficiently.
You can eager load relationships on existing models using load().