PHP

Optimize Relationship Queries with Eager Loading and Constraints

Learn to efficiently load related models in Laravel Eloquent using eager loading (`with`) and add specific conditions to the loaded relationships for optimized queries.

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

// Load users and their published posts
$users = User::with(['posts' => function ($query) {
    $query->where('is_published', true);
}])->get();

foreach ($users as $user) {
    echo "User: " . $user->name . "
";
    foreach ($user->posts as $post) {
        echo " - Post: " . $post->title . "
";
    }
}

// Load posts and their authors who are 'admin'
$posts = Post::with(['user' => function ($query) {
    $query->where('role', 'admin');
}])->get();

foreach ($posts as $post) {
    echo "Post: " . $post->title . "
";
    if ($post->user) {
        echo " - Author (Admin): " . $post->user->name . "
";
    }
}
How it works: Eager loading with constraints allows you to load related models in a single query while applying conditions to the *related* models. This prevents the 'N+1 query problem' and fetches only the relevant related data, improving application performance. The callback function within `with()` lets you add `where` clauses or other query builder methods to the relationship query.

Need help integrating this into your project?

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

Hire DigitalCodeLabs