PHP
Eager Loading Eloquent Relationships (`with()`)
Learn how to use Eloquent's `with()` method to eager load relationships, effectively solving the N+1 query problem and boosting application performance.
// Define a relationship in your User model
// public function posts() { return $this->hasMany(Post::class); }
// Bad: N+1 query problem
$users = App\Models\User::all();
foreach ($users as $user) {
echo $user->posts->count(); // Each $user->posts triggers a new query
}
// Good: Eager loading with 'with()'
$users = App\Models\User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count(); // Posts are already loaded, no extra queries
}
// Eager loading multiple relationships
$users = App\Models\User::with(['posts', 'comments'])->get();
// Eager loading nested relationships
$categories = App\Models\Category::with('posts.user')->get();
// Eager loading with constraints
$users = App\Models\User::with(['posts' => function ($query) {
$query->where('published_at', '<', now());
}])->get();
How it works: Eager loading relationships using the `with()` method significantly improves performance by reducing the number of database queries. Instead of fetching related models individually for each parent model (the N+1 problem), `with()` retrieves all related models in a single or a few separate queries, then efficiently matches them to their parents in memory. This is crucial for applications dealing with large datasets and complex relationships.