PHP
Efficiently Eager Load Eloquent Relationships to Prevent N+1 Queries
Learn how to use Eloquent's `with()` method to eager load related models, drastically improving performance by preventing the common N+1 query problem in Laravel applications.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
// Bad: N+1 problem - separate query for each user's posts
// $users = User::all();
// foreach ($users as $user) {
// echo $user->name . ' has ' . $user->posts->count() . ' posts.
';
// }
// Good: Eager load 'posts' relationship
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->name . ' has ' . $user->posts->count() . ' posts.
';
}
// Eager loading multiple relationships:
// $posts = Post::with(['user', 'comments'])->get();
// Eager loading with constraints:
// $users = User::with(['posts' => function ($query) {
// $query->where('is_published', true);
// }])->get();
return "Check your console/logs for output.";
}
}
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading relationships. Instead of making a separate database query for each related item (the 'N+1 problem'), eager loading fetches all related models in one or two additional queries, significantly boosting application performance, especially when dealing with many records. You can eager load single or multiple relationships, and even add constraints to the eager loaded relationships.