Reference / Laravel
Eloquent with() Eager Loading
Eager loads specified model relationships in a minimal number of optimized queries, preventing N+1 performance bottlenecks.
Syntax
Model::with(array|string $relations): BuilderParameters
| Name | Type | Description |
|---|---|---|
| relations | array|string | Relationship names or key-value closures for nested constraints. |
Examples
Constrained eager loading
$courses = Course::query()
->with([
'category:id,name,slug',
'lessons' => fn($q) => $q->where('status', 'published')->orderBy('sort_order')
])
->get();Always select the foreign key column when scoping select attributes inside eager loaded relationship closures.