PHP

Optimize N+1 Queries with Eager Loading Relationships and Constraints

Learn to efficiently load related Eloquent models using eager loading (`with()`) and apply custom constraints to the loaded relationships to filter data, preventing N+1 issues.

use App\Models\User;

$usersWithPublishedPosts = User::with(['posts' => function ($query) {
    $query->where('published', true);
}])->get();

foreach ($usersWithPublishedPosts as $user) {
    echo "User: " . $user->name . "
";
    foreach ($user->posts as $post) {
        echo "- Published Post: " . $post->title . "
";
    }
}
How it works: This snippet demonstrates how to use Eloquent's eager loading feature (`with()`) to fetch related models efficiently, avoiding the common N+1 query problem. It further shows how to apply constraints to the eager-loaded relationships (e.g., only fetching 'published' posts) by passing a closure to the `with()` method. This ensures that only relevant related data is loaded, improving performance significantly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs