PHPackages                             thybag/bonus-laravel-relations - 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. thybag/bonus-laravel-relations

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

thybag/bonus-laravel-relations
==============================

Additional eloquent ORM relation types for laravel.

0.5.1(7mo ago)733.1k—5.1%2[3 PRs](https://github.com/thybag/bonus-laravel-relations/pulls)MITPHPCI passing

Since Jul 1Pushed 3mo ago3 watchersCompare

[ Source](https://github.com/thybag/bonus-laravel-relations)[ Packagist](https://packagist.org/packages/thybag/bonus-laravel-relations)[ RSS](/packages/thybag-bonus-laravel-relations/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (31)Used By (0)

Bonus Eloquent relations for Laravel
====================================

[](#bonus-eloquent-relations-for-laravel)

A selection of weird &amp; wonderful additional relation types for laravel's eloquent ORM I've ended up needing.

Many of these are experimental and may behave in unexpected &amp; none standard ways.

On the bright side - it's tested!
[![Build Status](https://github.com/thybag/bonus-laravel-relations/actions/workflows/test.yml/badge.svg)](https://github.com/thybag/bonus-laravel-relations/actions/workflows/test.yml/badge.svg)

All licensed under the MIT license.

Usage.
------

[](#usage)

1. Install via composer using `composer require thybag/bonus-laravel-relations`
2. Include the `use thybag\BonusLaravelRelations\Traits\BonusRelationsTrait;` in to your model (or base model if you want them everywhere.)
3. Use the relations as you would any other.

The relation traits can also be added individually if you prefer that.

- Run tests with `composer test`
- Run lint with `composer lint`

Relations
=========

[](#relations)

### BelongsToMorph

[](#belongstomorph)

Get polymorphic relations of a single type.

```
public function shop()
{
    return $this->belongsToMorph(Shop::class, 'noteable');
}
```

### HasManyViaMany

[](#hasmanyviamany)

Define a relation via an unlimited number of middle tables.

```
public function products()
{
    return $this->hasManyViaMany(Product::class)->via(Shop::class)->via(Franchise::class);
}
```

### HasAggregate

[](#hasaggregate)

Get an aggregate result as a relation. The main benefit of this approach is it allows easy lazy loading of this data on collections + interaction with the results in a more eloquent like way.

```
public function productTotals()
{
    return $this->hasAggregate(Product::class)->selectRaw('
        COUNT(DISTINCT products.id) AS unique_products,
        SUM(products.amount) * AVG(products.value) AS stock_value,
        SUM(products.amount) AS total_products,
        AVG(products.value) AS average_product_value
    ');
}
```

Additional transformations on data returned from hasAggregate can be defined by using `withCallback(function($result){})` to define a transform function. Only one can be defined per relationship at present.

### HasMethod

[](#hasmethod)

Use a local method as if it were a relation.

```
public function totalValue()
{
    return $this->hasMethod(function () {
        return ['total' => ($this->amount * $this->value)];
    });
}
```

### BelongsToOne

[](#belongstoone)

Define a one-to-one relation through a pivot table.

```
public function latestRating()
{
    return $this->belongsToOne(Rating::class, 'shop_rating')->latest('created_at');
}
```

InertModel
==========

[](#inertmodel)

As the relationships `HasMethod` and `HasAggregate` don't return a traditional model from the database, a special model called type `InertModel` is used. This allows the relationship to fill the model with arbitrary attributes without the risk of causing unexpected behavior.

If you would like to use a custom InertModel rather than the one provided, create a config called `bonus-laravel-relationships.php` in your config folder, then set the value `inertModel` with the class path to the model you would like to use instead. I would recommend whatever model you use inherits from the base IntertModel to avoid unexpected behavior. Alternatively the `hasMethod` relationship supports a `withModel` or passing a `model` parameter to override this. Similar functionality is available in `hasAggrgegate` using the `returnModel` parameter.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance72

Regular maintenance activity

Popularity34

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% 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 ~120 days

Recently: every ~111 days

Total

23

Last Release

224d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e22d6c955042e97d5c5a68cc21b540dc6aa3fdb7f830d56274e51dbb6c10d13e?d=identicon)[bag](/maintainers/bag)

---

Top Contributors

[![thybag](https://avatars.githubusercontent.com/u/887397?v=4)](https://github.com/thybag "thybag (24 commits)")[![vroomfondle](https://avatars.githubusercontent.com/u/6186584?v=4)](https://github.com/vroomfondle "vroomfondle (5 commits)")[![Xulai](https://avatars.githubusercontent.com/u/5481226?v=4)](https://github.com/Xulai "Xulai (5 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

eloquentlaravel

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/thybag-bonus-laravel-relations/health.svg)

```
[![Health](https://phpackages.com/badges/thybag-bonus-laravel-relations/health.svg)](https://phpackages.com/packages/thybag-bonus-laravel-relations)
```

###  Alternatives

[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[staudenmeir/eloquent-json-relations

Laravel Eloquent relationships with JSON keys

1.1k5.8M24](/packages/staudenmeir-eloquent-json-relations)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.1M11](/packages/bavix-laravel-wallet)[dragon-code/migrate-db

Easy data transfer from one database to another

15717.4k](/packages/dragon-code-migrate-db)[gearbox-solutions/eloquent-filemaker

A package for getting FileMaker records as Eloquent models in Laravel

6454.8k2](/packages/gearbox-solutions-eloquent-filemaker)[cybercog/laravel-ownership

Laravel Ownership simplify management of Eloquent model's owner.

9126.6k3](/packages/cybercog-laravel-ownership)

PHPackages © 2026

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