PHP

Optimize Database Queries with Eloquent Eager Loading

Learn how to prevent the N+1 query problem in Laravel Eloquent by using eager loading with the `with()` method to efficiently load related models and improve performance.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Post;

class UserController extends Controller
{
    public function index()
    {
        // Bad: N+1 problem (fetches all users, then one query per user for posts)
        // $users = User::all();
        // foreach ($users as $user) {
        //     echo $user->name . ': ' . $user->posts->count() . "
";
        // }

        // Good: Eager loading 'posts' relationship
        $users = User::with('posts')->get();

        foreach ($users as $user) {
            echo $user->name . ': ' . $user->posts->count() . "
";
        }

        // Eager load multiple relationships
        $postsWithCommentsAndUser = Post::with(['comments', 'user'])->get();

        foreach ($postsWithCommentsAndUser as $post) {
            echo "Post: {$post->title}, User: {$post->user->name}, Comments: {$post->comments->count()}
";
        }

        return "Data fetched successfully. Check console/logs.";
    }
}

// In your User model (App\Models\User.php):
// public function posts()
// {
//     return $this->hasMany(Post::class);
// }

// In your Post model (App\Models\Post.php):
// public function user()
// {
//     return $this->belongsTo(User::class);
// }
// public function comments()
// {
//     return $this->hasMany(Comment::class);
// }
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading relationships. Without eager loading, fetching a collection of models and then accessing a related model for each item (e.g., `User::all()` then `foreach ($user->posts)`) leads to the N+1 query problem, where N additional queries are run. Eager loading retrieves all related models in a single, separate query, drastically reducing database load and improving application performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs