PHP

Efficient Eager Loading of Specific Columns and Nested Relationships in Eloquent

Optimize database queries by eager loading only necessary columns and applying constraints on nested relationships, reducing memory usage and improving performance.

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

// Eager load 'user' relation with only 'id' and 'name' columns.
// Eager load 'comments' relation, filter by 'approved', and select specific columns.
// Eager load 'comments.author' relation with only 'id' and 'email' columns.
$posts = Post::with([
    'user:id,name',
    'comments' => function ($query) {
        $query->where('approved', true)->select('id', 'post_id', 'body');
    },
    'comments.author:id,email'
])->get();

foreach ($posts as $post) {
    echo $post->user->name . " has " . $post->comments->count() . " approved comments.
";
    foreach ($post->comments as $comment) {
        echo " - Comment by " . $comment->author->email . ": " . $comment->body . "
";
    }
}
How it works: This snippet demonstrates advanced eager loading techniques. It shows how to load only specific columns from a related model using the `relation:column1,column2` syntax, which reduces the data fetched. Furthermore, it illustrates applying a `where` clause directly to an eager-loaded relationship and nesting eager loading for deeply related models (`comments.author`), all within a single query.

Need help integrating this into your project?

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

Hire DigitalCodeLabs