← Back to all snippets
PHP

Efficient Eager Loading with Constraints & Specific Columns

Optimize Laravel Eloquent queries by eagerly loading related models with specific conditions and only fetching necessary columns to reduce memory usage.

$users = App\Models\User::with([
    'posts' => function ($query) {
        $query->where('published', true)->select('id', 'user_id', 'title', 'created_at');
    },
    'comments' => function ($query) {
        $query->where('approved', true)->select('id', 'post_id', 'user_id', 'body');
    }
])->get();

foreach ($users as $user) {
    echo "User: " . $user->name . "
";
    foreach ($user->posts as $post) {
        echo "  - Post: " . $post->title . " (Published: " . $post->created_at->format('Y-m-d') . ")
";
    }
    foreach ($user->comments as $comment) {
        echo "  - Comment: " . $comment->body . "
";
    }
}
How it works: This snippet demonstrates how to eagerly load relationships in Laravel Eloquent while applying specific conditions to the related models and selecting only a subset of their columns. This significantly optimizes query performance and memory usage by fetching only the relevant data, avoiding the N+1 problem and unnecessary data transfer.

Need help integrating this into your project?

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

Hire DigitalCodeLabs