PHP

Optimize Eloquent Queries with Eager Loading & Constraints

Learn how to prevent the N+1 query problem in Laravel Eloquent by efficiently loading related models with specific conditions, drastically improving application performance.

<?php

// Example: User model has many Post models
// User.php
// public function posts() { return $this->hasMany(Post::class); }

// Basic eager loading
$usersWithPosts = App\Models\User::with('posts')->get();

// Eager loading with specific columns and constraints
$activeUsersWithPublishedPosts = App\Models\User::with(['posts' => function ($query) {
    $query->where('status', 'published')->select('id', 'user_id', 'title', 'created_at');
}])->where('active', 1)->get();

// Accessing data
foreach ($activeUsersWithPublishedPosts as $user) {
    echo $user->name . " has published posts:
";
    foreach ($user->posts as $post) {
        echo "- " . $post->title . " (published on " . $post->created_at->format('Y-m-d') . ")
";
    }
}
How it works: This snippet demonstrates efficient eager loading in Laravel Eloquent to prevent the N+1 query problem. By using the `with()` method, you can load related models alongside the parent model in a single query. The example also shows how to add constraints to the eager-loaded relationship (e.g., `where('status', 'published')`) and select only specific columns, further optimizing database queries and reducing memory usage.

Need help integrating this into your project?

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

Hire DigitalCodeLabs