audunru/eager-load-pivot-relations
BelongsToMany relationships where pivots have nested relations (e.g., procurement systems with unit conversions, inventory with variant attributes). Critical for APIs serving high-traffic dashboards or real-time data.plan_item pivots with unit relations (e.g., Plan::with('items.pivot.unit')->get()).order_item pivots with variant attributes (e.g., Order::with('items.pivot.variant')->get()).tenant_feature with activation_date).post_tag pivots with category relations).user_event pivots with event_type details).Adopt When:
BelongsToMany pivots contain relations or custom attributes that trigger N+1 queries (e.g., pivots with belongsTo, hasMany, or extra columns like price, status).Look Elsewhere When:
withPivot().For Executives: "This package solves a critical performance gap in our Laravel backend. By eliminating N+1 queries for complex pivot relationships—like procurement plans with unit conversions or inventory items with variants—we’ll reduce API response times by 30–50% for high-traffic features. For example, loading a procurement plan with 100 items and their units will now require 1 query instead of 101, directly improving dashboard performance and scalability. It’s a low-risk, high-reward upgrade that aligns with our roadmap for data-rich systems."
For Engineers: *"This is a drop-in solution for eager-loading pivot relations in Laravel. Key benefits:
BelongsToMany pivots with relations (e.g., Plan::with('items.pivot.unit')).with('relation.pivot.relation').pivot to planItem or other aliases via ->as().Use it when pivots have behavior beyond foreign keys (e.g., unit_id, quantity, or nested relations). Avoid if pivots are trivial. Example:
// Before (N+1 queries):
$plan = Plan::with('items')->get();
foreach ($plan->items as $item) {
$unit = $item->pivot->unit; // Triggers N+1!
}
// After (1 query):
$plan = Plan::with('items.pivot.unit')->get();
$unit = $plan->items->first()->pivot->unit; // Instant!
```*
**For Product Managers**:
*"This enables us to **build richer data models without sacrificing performance**. For example:
- **Procurement**: Show unit conversions (pc/box) inline with items.
- **E-Commerce**: Display variant attributes (size/color) without extra API calls.
- **Subscriptions**: Fetch tier-specific metadata (e.g., `discount_code`) in plan listings.
It’s a **force multiplier** for features that rely on complex relationships, reducing dev time and improving UX."*
How can I help you explore Laravel packages today?