PHPackages                             balfour/eloquent-dynamic-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. balfour/eloquent-dynamic-relationships

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

balfour/eloquent-dynamic-relationships
======================================

A library for monkey patching relationships between Eloquent models at runtime

0.0.1-alpha(6y ago)111MITPHP

Since Feb 26Pushed 6y ago6 watchersCompare

[ Source](https://github.com/balfour-group/eloquent-dynamic-relationships)[ Packagist](https://packagist.org/packages/balfour/eloquent-dynamic-relationships)[ RSS](/packages/balfour-eloquent-dynamic-relationships/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

balfour/eloquent-dynamic-relationships
======================================

[](#balfoureloquent-dynamic-relationships)

A library for monkey patching relationships between Eloquent models at runtime.

You can use this library inside any Laravel application or stand-alone application which uses the Eloquent ORM.

*This library is in early release and is pending unit tests.*

Use Case
--------

[](#use-case)

We developed this library when a need arose to bond models separated across multiple packages (and repositories) in an internal modular system.

Let's consider a system such as the following:

- The `framework` - the brain which glues modules together.
- A `user` module - a package which allows users to login, register, etc.
- A `sms` module - a package which allows users to send text messages.

These are 3 separate packages stored in independent repositories which have the bare minimum knowledge of each other.

- The `framework` knows about both `user` and `sms` modules.
- The `user` module has no dependencies.
- The `sms` module knows about the `user` module.

In this system, the *Message* model can define it's **many to one** relationship to the *User* model; however the *User* model has no context of the `sms` package and is therefore not capable of defining the inverse **one to many** relationship back.

eg: `$message->user` would succeed, but `$user->messages` or `$user->messages()->paginate()`would cause an error.

The responbility therefore falls on the `framework` to monkey patch this inverse relationship on the *User* model.

Installation
------------

[](#installation)

```
composer require balfour/eloquent-dynamic-relationships
```

This package only needs to be installed in the repository (or repositories) containing models you want to make monkey patachable.

Usage
-----

[](#usage)

### Configuring Monkey Patachable Model

[](#configuring-monkey-patachable-model)

The model which you want to make monkey patchable needs to either extend our base model, or use the `HasDynamicRelationships` trait.

**Method 1 (preferred)**

```
namespace SMSModule;

use Balfour\EloquentDynamicRelationships\HasDynamicRelationships;
use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    use HasDynamicRelationships;

    //
}
```

**Method 2**

```
namespace SMSModule;

use Balfour\EloquentDynamicRelationships\Model;

class Message extends Model
{
    //
}
```

### Creating Dynamic Relationship

[](#creating-dynamic-relationship)

In your framework codebase which glues everything together, you'll need to bond the two models together. This should typically be done at a bootstrap stage, such as when your app's `AppServiceProvider` is booted.

```
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use SMSModule\Message;
use UserModule\User;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        UserModule::bond('messages', function () {
            return $this->hasMany(Message::class);
        });
    }
}
```

With the bond established between the 2 models, you can now use relationship calls as per normal.

eg:

```
use SMSModule\Message;
use UserModule\User;

$user = User::find(1);

// retrieve a user's messages
$messages = $user->messages;

// retrieve and sort a user's messages by send date
$messages = $user->messages()
    ->latest('send_date')
    ->get();

// paginate a user's messages
$messages = $user->messages()
    ->paginate();

// get the user who sent the message
$message = Message::first();
$user = $message->user;
```

### Other Methods

[](#other-methods)

```
use UserModule\User;

// destroy a bond between 2 models
User::breakup('activities');

// retrieve all dynamic bonds
$bonds = User::getBonds();

// determine if a model is bonded with another
User::isBondedWith('activities');
```

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

2267d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/054093c4138d9bea138f6226b632f8f7ad0adb516562480f7f77868d481e75f0?d=identicon)[balfourgroup](/maintainers/balfourgroup)

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/balfour-eloquent-dynamic-relationships/health.svg)

```
[![Health](https://phpackages.com/badges/balfour-eloquent-dynamic-relationships/health.svg)](https://phpackages.com/packages/balfour-eloquent-dynamic-relationships)
```

###  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)
