๐ 2 minutes read
When certain relationships are always needed with a model, you can eager load them by default using the protected $with property instead of adding with() to every query.
The Pattern
Add the $with property to your model:
class User extends Model
{
protected $with = ['profile'];
public function profile(): BelongsTo
{
return $this->belongsTo(Profile::class);
}
}
Now every query automatically eager loads the profile:
// These all include profile automatically:
User::find(1);
User::all();
User::where('active', true)->get();
// No N+1 queries! Profile is always loaded.
When to Use This
Perfect for:
- API resources that always serialize certain relations
- Computed attributes that depend on relationships
- Models with logical “parent” relationships
Example use case: A Comment model where you always need the author:
class Comment extends Model
{
protected $with = ['author'];
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
}
Disable When Needed
You can still opt out of auto-eager loading in specific queries:
// Skip the default eager load:
User::without('profile')->get();
Trade-offs
Pros: Cleaner code, prevents forgotten eager loads, consistent behavior
Cons: Always eager loads, even when not neededโcan add overhead if overused
Best practice: Combine protected $with for “always needed” relations with whenLoaded() in resources for “sometimes needed” ones.
Leave a Reply