← Back to all snippets
PHP

Optimizing Eloquent Queries with Eager Loading Constraints

Learn to solve the N+1 problem efficiently in Laravel Eloquent by eager loading relationships, applying specific constraints to the related models to fetch only necessary data.

$users = App\Models\User::with(['posts' => function ($query) {
    $query->where('published', true)->orderBy('created_at', 'desc');
}])->get();

foreach ($users as $user) {
    foreach ($user->posts as $post) {
        // Access published posts for each user
        // echo $post->title;
    }
}
How it works: This snippet demonstrates how to eager load a relationship ('posts') while applying additional constraints to the related models. The closure passed to with() allows you to add WHERE clauses or ORDER BY conditions, ensuring only specific related data is fetched. This prevents the N+1 query problem, significantly optimizing database performance by reducing the number of queries executed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs