PHP
Optimize Database Queries with Eloquent Eager Loading and Constraints
Prevent N+1 query problems in Laravel by efficiently loading related models with Eloquent eager loading, including custom constraints for specific data filtering.
$users = App\Models\User::with(['posts' => function ($query) {
$query->where('published', true);
}])->get();
foreach ($users as $user) {
echo $user->name . ' has published ' . $user->posts->count() . ' posts.';
}
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading relationships, which efficiently prevents the N+1 query problem by fetching all related models in a minimal number of queries. It also shows how to add constraints to the eager-loaded relationship, allowing you to filter the related models based on specific conditions directly within the eager loading query, ensuring only relevant data is fetched.