PHPackages                             rdx/laravel-aggregate-relationships - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. rdx/laravel-aggregate-relationships

ActiveLibrary[Database &amp; ORM](/categories/database)

rdx/laravel-aggregate-relationships
===================================

Make COUNT() and SUM() etc relationships in Laravel, without withCount()

1.13(4mo ago)313.9k↓13.6%[1 issues](https://github.com/rudiedirkx/laravel-aggregate-relationships/issues)MITPHPPHP ^8.0

Since Dec 29Pushed 4mo agoCompare

[ Source](https://github.com/rudiedirkx/laravel-aggregate-relationships)[ Packagist](https://packagist.org/packages/rdx/laravel-aggregate-relationships)[ RSS](/packages/rdx-laravel-aggregate-relationships/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (15)Used By (0)

Aggregate relationships in Laravel
==================================

[](#aggregate-relationships-in-laravel)

What? - Laravel already has relationships
-----------------------------------------

[](#what---laravel-already-has-relationships)

Laravel can make relationships to other models, but not to scalars (e.g. numbers). This package can `COUNT()` and `SUM()` relationships. Especially `COUNT()` is useful, because duh.

Why? - Laravel has this!
------------------------

[](#why---laravel-has-this)

No. The only way in Laravel to count a relationship is with `withCount()`, which...

- only work for **eager** loading, not lazy
- can't be called after the objects exists, on the collection (like `->load('name')`)
- are always named `{name}_count`

How?
----

[](#how)

Add the trait to your models/base model:

```
use RelatesToAggregates;
```

This exposes methods `hasCount(relatedClass, foreignKey)`, `hasAggregate(relatedClass, aggregateColumn, foreignKey)` and `hasManyScalar(targetKey, targetTable, foreignKey)`:

Define the relationship:

```
class User extends Model {
	use RelatesToAggregates;

	// Number of transactions for this user
	function num_transactions() {
		return $this->hasCount(Transaction::class, 'user_id');
	}

	// Sum of all positive and negative transactions for this user
	function current_balance() {
		return $this->hasAggregate(Transaction::class, 'sum(money_change)', 'user_id');
	}

	// List of payment uuids
	function payment_refs() {
		return $this->hasManyScalar('reference_uuid', 'transactions', 'user_id');
	}
}
```

And then eager load it **like normal relationships**:

```
$users = User::with(['address', 'fav_color', 'num_transactions', 'current_balance', 'payment_refs'])->get();
```

or later, **like normal relationships**, unlike Laravel's count:

```
$users = User::all();
$users->load(['address', 'fav_color', 'num_transactions', 'current_balance', 'payment_refs']);
```

and if you can't/don't want to eager load it, lazy load it, **like a normal relationship**:

```
$user = User::find(123);
echo "Balance: {$user->current_balance} ({$user->num_transactions} transactions): " .
	implode(', ', $user->payment_refs);
```

Recap
-----

[](#recap)

- Eager AND lazy loading
- Eager loadable on existing collection
- Custom names

**Like a real relationship!**

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance70

Regular maintenance activity

Popularity29

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~197 days

Recently: every ~112 days

Total

14

Last Release

125d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/78549c1dc5c83ec0201c9afc66762c6d5bbf770291b12bae5a7a65350f950dba?d=identicon)[rudiedirkx](/maintainers/rudiedirkx)

---

Top Contributors

[![rudiedirkx](https://avatars.githubusercontent.com/u/168024?v=4)](https://github.com/rudiedirkx "rudiedirkx (23 commits)")

### Embed Badge

![Health badge](/badges/rdx-laravel-aggregate-relationships/health.svg)

```
[![Health](https://phpackages.com/badges/rdx-laravel-aggregate-relationships/health.svg)](https://phpackages.com/packages/rdx-laravel-aggregate-relationships)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
