PHPackages                             mr-punyapal/laravel-extended-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. mr-punyapal/laravel-extended-relationships

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

mr-punyapal/laravel-extended-relationships
==========================================

Package provides additional, more efficient relationship methods for Laravel Eloquent models.

2.2.0(1mo ago)17310.1k↓27.4%9[1 issues](https://github.com/MrPunyapal/laravel-extended-relationships/issues)MITPHPPHP ^8.2|^8.3|^8.4|^8.5CI passing

Since Apr 2Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/MrPunyapal/laravel-extended-relationships)[ Packagist](https://packagist.org/packages/mr-punyapal/laravel-extended-relationships)[ Docs](https://github.com/mrpunyapal/laravel-extended-relationships)[ GitHub Sponsors](https://github.com/mrpunyapal)[ RSS](/packages/mr-punyapal-laravel-extended-relationships/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (18)Versions (14)Used By (0)

laravel-extended-relationships
==============================

[](#laravel-extended-relationships)

[![Latest Version on Packagist](https://camo.githubusercontent.com/688d556f52ad990aac944667b6a656efdad043bba3ebb0be56d30a4db7e1ddaf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d722d70756e796170616c2f6c61726176656c2d657874656e6465642d72656c6174696f6e73686970732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mr-punyapal/laravel-extended-relationships)[![GitHub Tests Action Status](https://camo.githubusercontent.com/8780de2033125170e24660b36cf67a5803d262a50183d68df10a28b9457522fc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d722d70756e796170616c2f6c61726176656c2d657874656e6465642d72656c6174696f6e73686970732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mr-punyapal/laravel-extended-relationships/actions?query=workflow%3Arun-tests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/9a9a7b906a6f4f1aacac3a9f16acc56241515a75168ade5b0e3062db2787a17e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d722d70756e796170616c2f6c61726176656c2d657874656e6465642d72656c6174696f6e73686970732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mr-punyapal/laravel-extended-relationships)

Requirements
------------

[](#requirements)

- PHP: ^8.2|^8.3|^8.4|^8.5
- Laravel: ^11.0|^12.0|^13.0

### What is a need of extended relationships?

[](#what-is-a-need-of-extended-relationships)

The laravel-extended-relationships package provides additional, more efficient relationship methods for Laravel Eloquent models. The package offers several useful features such as reducing the number of database queries, improving performance, and minimizing duplicate code.

I faced issue and made my own relationships then realize if I can use packages from open source then I can make one too and made this package.

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

[](#installation)

You can install the package via composer:

```
composer require mrpunyapal/laravel-extended-relationships
```

Usage
-----

[](#usage)

First, include the `HasExtendedRelationships` trait in your model:

```
use MrPunyapal\LaravelExtendedRelationships\HasExtendedRelationships;

class Post extends Model {
    use HasExtendedRelationships;

    //...
}
```

Next, define the `BelongsToManyKeys` relationship with the `belongsToManyKeys` method:

```
public function auditors() {
    return $this->belongsToManyKeys(
        related: User::class,
        foreignKey: 'id',
        relations: [
            'created_by' => 'creator',
            'updated_by' => 'updater',
            'deleted_by' => 'deleter',
        ]
    );
}
```

### This method takes three arguments:

[](#this-method-takes-three-arguments)

- The related model (`User::class`)
- The foreign key (`id`)
- An array mapping the related table's foreign key names to the corresponding relation names on the model (`['created_by' => 'creator', ...]`)

### Then, you can fetch data from the auditors relationship like so:

[](#then-you-can-fetch-data-from-the-auditors-relationship-like-so)

```
$post = Post::with('auditors')->first();

// Get the creator
$post->auditors->creator;

// Get the updater
$post->auditors->updater;

// Get the deleter
$post->auditors->deleter;

// also works with lazy loading

$post = Post::find(7);

// Get the creator
$post->auditors->creator;

// Get the updater
$post->auditors->updater;

// Get the deleter
$post->auditors->deleter;
```

This allows you to define multiple relationships with just one method, and only a single query is fired in the database for all the relationships.

### Inverse relationship.

[](#inverse-relationship)

```
use MrPunyapal\LaravelExtendedRelationships\HasExtendedRelationships;

class User extends Model{

    use HasExtendedRelationships;

    public function audited(){
        return $this->hasManyKeys(
            related: Post::class,
            relations: [
                'created_by' => 'created',
                'updated_by' => 'updated',
                'deleted_by' => 'deleted',
            ],
            localKey: 'id'
        );
    }
}
```

To retrieve the audited posts of a user, you can use the audited relationship. Here's an example:

```
$user = User::with('audited')->first();

// Get posts created by the user
$user->audited->created;

// Get posts updated by the user
$user->audited->updated;

// Get posts deleted by the user
$user->audited->deleted;

// also works with lazy loading

$user = User::find(71);

// Get posts created by the user
$user->audited->created;

// Get posts updated by the user
$user->audited->updated;

// Get posts deleted by the user
$user->audited->deleted;
```

This allows you to define multiple relationships between models with a single method call, simplifying your code and reducing the number of queries executed.

### HasManyArrayColumn

[](#hasmanyarraycolumn)

If you have a column companies in your users table which stores an array of local keys like \[7, 71\] or \["7", "71"\], you can use the following relationship:

```
use MrPunyapal\LaravelExtendedRelationships\HasExtendedRelationships;

class User extends Model
{
    use HasExtendedRelationships;

    protected $casts=[
       'companies' => 'array'
    ];

    public function myCompanies()
    {
        return $this->hasManyArrayColumn(
            related: Company::class,
            foreignKey: 'id',
            localKey: 'companies'
        );
    }
}
```

When fetching data, you can retrieve the related companies with:

```
$user = User::with('myCompanies')->first();

// get companies with ids 7 and 71
$user->myCompanies;
```

This allows you to easily retrieve related records with an array of local keys, which can be useful in certain scenarios.

### Inverse Relationship for `HasManyArrayColumn`

[](#inverse-relationship-for-hasmanyarraycolumn)

The `BelongsToArrayColumn` method allows you to define a relationship between a model and an array column on another model. if you have \["7", "71"\] in array column and int 7 or 71 at your foreign-key then pass `$isString` flag as true to get expected results.

Here's an example:

```
use MrPunyapal\LaravelExtendedRelationships\HasExtendedRelationships;

class Company extends Model
{
    use HasExtendedRelationships;

    public function companyFounders()
    {
        return $this->belongsToArrayColumn(
            related: User::class,
            foreignKey: 'id',
            localKey: 'companies',
            // optional, default is false (if true then it treats all values as string)
            isString: true
        );
    }
}
```

With this relationship defined, you can fetch related company founders with the following code:

```
$company = Company::with('companyFounders')->find(71);

// Founders for company with id 71

$company->companyFounders;
```

This will provide you with data from the `users` table where the `companies` array column contains the value 71.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [MrPunyapal](https://github.com/MrPunyapal)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

58

—

FairBetter than 98% of packages

Maintenance89

Actively maintained with recent releases

Popularity42

Moderate usage in the ecosystem

Community16

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 92.9% 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 ~99 days

Total

12

Last Release

56d ago

Major Versions

1.4 → 2.0.02025-06-02

PHP version history (5 changes)1.0.1PHP ^8.1

1.3PHP ^8.1|^8.2|^8.3

1.4PHP ^8.1|^8.2|^8.3|^8.4

2.0.0PHP ^8.2|^8.3|^8.4

2.1.0PHP ^8.2|^8.3|^8.4|^8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/230c58a4f918ca3e3f2988b38721230698bce88f76ae9087e4377ba0b3a074d5?d=identicon)[MrPunyapal](/maintainers/MrPunyapal)

---

Top Contributors

[![MrPunyapal](https://avatars.githubusercontent.com/u/53343069?v=4)](https://github.com/MrPunyapal "MrPunyapal (156 commits)")[![hosmelq](https://avatars.githubusercontent.com/u/1166143?v=4)](https://github.com/hosmelq "hosmelq (6 commits)")[![tanghengzhi](https://avatars.githubusercontent.com/u/2969338?v=4)](https://github.com/tanghengzhi "tanghengzhi (4 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (2 commits)")

---

Tags

belongstobelongstomanyeloquenthasmanyhasonelaravelphprelationshipsjsonlaraveleloquentrelationshiphas-manyeloquent-relationshipslaravel-extended-relationshipsMrPunyapal

###  Code Quality

TestsPest

Static AnalysisRector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mr-punyapal-laravel-extended-relationships/health.svg)

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

###  Alternatives

[silber/bouncer

Eloquent roles and abilities.

3.6k4.4M25](/packages/silber-bouncer)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[lacodix/laravel-model-filter

A Laravel package to filter, search and sort models with ease while fetching from database.

17649.9k](/packages/lacodix-laravel-model-filter)[io238/laravel-iso-countries

Ready-to-use Laravel models and relations for country (ISO 3166), language (ISO 639-1), and currency (ISO 4217) information with multi-language support.

5462.3k](/packages/io238-laravel-iso-countries)[cviebrock/eloquent-typecast

Trait for Eloquent models to force type-casting on retrieved values

2468.0k](/packages/cviebrock-eloquent-typecast)

PHPackages © 2026

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