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.6.0(1w ago)735.6k↓37.7%2[3 PRs](https://github.com/thybag/bonus-laravel-relations/pulls)MITPHPCI passing

Since Jul 1Pushed 5mo 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 today

READMEChangelog (10)Dependencies (8)Versions (33)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

53

—

FairBetter than 96% of packages

Maintenance84

Actively maintained with recent releases

Popularity35

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity64

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 ~126 days

Recently: every ~149 days

Total

24

Last Release

8d 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

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.4M96](/packages/mongodb-laravel-mongodb)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k32.6M46](/packages/kirschbaum-development-eloquent-power-joins)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)[awobaz/compoships

Laravel relationships with support for composite/multiple keys

1.2k11.7M47](/packages/awobaz-compoships)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.3M19](/packages/bavix-laravel-wallet)[glushkovds/phpclickhouse-laravel

Adapter of the most popular library https://github.com/smi2/phpClickHouse to Laravel

2051.5M2](/packages/glushkovds-phpclickhouse-laravel)

PHPackages © 2026

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