Laravel - Relationships - Constraining Eager Loads

Sometimes you may wish to eager load a relationship but also specify additional query conditions for the eager loading query. You can accomplish this by passing an array of relationships to the with method where the array key is a relationship name and the array value is a closure that adds additional constraints to the eager loading query:

    
    use App\Models\User;
    
    $users = User::with(['posts' => function ($query) {
        $query->where('title', 'like', '%code%');
    }])->get();
	

In this example, Eloquent will only eager load posts where the post's title column contains the word code. You may call other query builder methods to further customize the eager loading operation:

    
    $users = User::with(['posts' => function ($query) {
        $query->orderBy('created_at', 'desc');
    }])->get();
	
The limit and take query builder methods may not be used when constraining eager loads.