PHP
Eager Loading Relationships with Specific Conditions
Optimize database queries by eagerly loading Eloquent relationships with specific WHERE conditions, reducing N+1 query problems and enhancing performance.
use App\Models\User;
use App\Models\Post;
// Load users and only their published posts
$users = User::with(['posts' => function ($query) {
$query->where('status', 'published');
}])->get();
foreach ($users as $user) {
echo "User: " . $user->name . "
";
foreach ($user->posts as $post) {
echo "- Published Post: " . $post->title . "
";
}
}
// You can also chain further constraints or ordering on the eager loaded relation
$products = Product::with(['reviews' => function ($query) {
$query->where('rating', '>=', 4)->orderBy('created_at', 'desc');
}])->get();
How it works: This snippet demonstrates how to eagerly load relationships in Laravel Eloquent, but with an added constraint. Instead of loading all related records, you can pass a closure to the `with()` method to apply specific conditions (like a `where` clause or `orderBy`) to the relationship query. This is incredibly useful for filtering related data efficiently and avoiding the N+1 query problem while still only fetching relevant sub-data from the database.