PHPackages                             kingmaker/laravel-many-to-many-self-relationship - 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. kingmaker/laravel-many-to-many-self-relationship

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

kingmaker/laravel-many-to-many-self-relationship
================================================

Laravel Many to Many Relationship on the same Model through a pivot table providing two-way association.

2.1.8(4mo ago)19103.2k↑32.7%2[1 issues](https://github.com/kingmaker-agm/laravel-many-to-many-self/issues)MITPHPPHP ^7.2|^8.0CI passing

Since May 28Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/kingmaker-agm/laravel-many-to-many-self)[ Packagist](https://packagist.org/packages/kingmaker/laravel-many-to-many-self-relationship)[ Docs](https://github.com/kingmaker-agm/laravel-many-to-many-self)[ RSS](/packages/kingmaker-laravel-many-to-many-self-relationship/feed)WikiDiscussions 2.1+ Synced 2w ago

READMEChangelogDependencies (6)Versions (22)Used By (0)

Laravel Many to Many Self Relationship
======================================

[](#laravel-many-to-many-self-relationship)

[![Version](https://camo.githubusercontent.com/d699b2ead3a184cc99170648066a2fc23f814e85ec98c052efa4d9836f27b70f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f56657273696f6e2d322e312d627269676874677265656e)](https://packagist.org/packages/kingmaker/laravel-many-to-many-self-relationship)[![Packagist Downloads](https://camo.githubusercontent.com/dcb70d7fda30f23a1bf236c787c595931fbfd8c6afed540e0877e431a25c90b0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6b696e676d616b65722f6c61726176656c2d6d616e792d746f2d6d616e792d73656c662d72656c6174696f6e73686970)](https://camo.githubusercontent.com/dcb70d7fda30f23a1bf236c787c595931fbfd8c6afed540e0877e431a25c90b0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6b696e676d616b65722f6c61726176656c2d6d616e792d746f2d6d616e792d73656c662d72656c6174696f6e73686970)[![Laravel](https://camo.githubusercontent.com/ab86c283577907b4b26cb0b890a7cb955acc67132051c3b51fef96a29705392f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d362532422d666636393462)](https://laravel.com/)[![Run PHPUnit Tests](https://github.com/kingmaker-agm/laravel-many-to-many-self/actions/workflows/run-tests.yml/badge.svg)](https://github.com/kingmaker-agm/laravel-many-to-many-self/actions/workflows/run-tests.yml)[![License](https://camo.githubusercontent.com/d6bc2b26794002c24d023acaab01b6dbb953c57ab9cb80ba5b8aa2f2bd5de99a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c7565)](https://opensource.org/licenses/MIT)

This package includes an extension to the `belongsToMany` Relationship of the Laravel allowing **two-way association** between the same model with a single Entry on the pivot table.

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

[](#installation)

The package can be installed via Composer.

```
composer require kingmaker/laravel-many-to-many-self-relationship
```

Version
-------

[](#version)

This package is available on specific Laravel versions.

Package VersionLaravel Version1.x6.20+ or 7.29+2.0.x8.17 - 8.342.1+8.35+ or 9+Usage
-----

[](#usage)

Include the `HasBelongsToManySelfRelation` trait in the **Model class** and define the relation method as follows:

```
use Illuminate\Database\Eloquent\Model;
use Kingmaker\Illuminate\Eloquent\Relations\HasBelongsToManySelfRelation;

class Post extends Model {

    use HasBelongsToManySelfRelation;

    public function relatedPosts()
    {
        return $this->belongsToManySelf('related_posts', 'post1', 'post2');
    }
}
```

It is that simple and has all the Methods available on the `belongsToMany()`. The Related Posts can be accessed like any normal relation.

```
$post = Post::first();
$post->relatedPosts; // returns Collection of Related Posts
```

> This is an extension over the native `BelongsToMany` class provided by the Eloquent.

Example
-------

[](#example)

Consider there are 'posts' table and 'related\_posts' table. The Post represent Post in the blog and it can have related posts similar to them.

```
posts:
| id | title | body |
+----+-------+------+
| 1  | a     | ...  |
| 2  | b     | ...  |
| 3  | c     | ...  |
| 4  | d     | ...  |
+----+-------+------+

related_posts:
| id | post1 | post2 |
+----+-------+-------+
| 1  | 1     | 3     |
| 2  | 1     | 4     |
| 3  | 2     | 1     |
| 4  | 2     | 3     |
| 5  | 3     | 4     |
| 6  | 4     | 2     |
+----+-------+-------+
```

The `belongsToManySelf` relation provides **two-way association** when calling the Relation.

```
Post::find(1)->relatedPosts; // returns Posts with id 2, 3, 4
Post::find(2)->relatedPosts; // returns Posts with id 1, 3, 4
Post::find(3)->relatedPosts; // returns Posts with id 1, 2, 4
Post::find(4)->relatedPosts; // returns Posts with id 1, 2, 3
```

Caution
-------

[](#caution)

There is a possibility for the returning of *duplicate related object*if the entities are related by 2rows on the Pivot table.

Use Cases
---------

[](#use-cases)

This **two-way associated** Many-to-Many relationship can be used in few peculiar situations. This relation doesn't suit all the Scenarios.

### a) Related Posts / Products

[](#a-related-posts--products)

Consider a blog or shopping website, where we have *post / product* related to each other. When the related Entity is matched via `BelongsToMany` relationship, the association of one Post/Product as related to the other post/product, on fetching the *relatedPost* or *relatedProduct* from the first Object will yield the second, but the inverse is not true (*ie, getting first post/product as related post/product from the second*)

### b) Friend list in social media

[](#b-friend-list-in-social-media)

In Social Media, the concept of Users being friended to one another can be easily achieved using this relation (not followers &amp; following, just mutual friends). Once a Users add another User as friends, we can attach the User and doesn't need to care about the attachment of reverse while using this relationship.

> **Note**: The Concept of *followers* and *following* has to use the Laravel's `BelongsToMany` relation. This relation is for *friends* like in Facebook.

### c) Messages in a Chat

[](#c-messages-in-a-chat)

The Message in a Chat application, where a message is directed from a User to another User. This relation lets you retrieve all the Users that have messaged a particular User.

> **Note**: There may be possibility of duplicates in this case

API Reference
-------------

[](#api-reference)

The trait `HasBelongsToManySelfRelation` adds the method `belongsToManySelf` to your Model.

```
    /**
     * create the BelongsToManySelf relation on the same Model via a pivot table
     *
     * @param string $table Pivot table name
     * @param string $pivotKey1 Pivot table foreign key 1
     * @param string $pivotKey2 Pivot table foreign key 2
     * @param string|null $relatedKey Related key on the parent table
     * @param string|null $relation Relation name
     * @return BelongsToManySelf
     */
    public function belongsToManySelf(string $table, string $pivotKey1, string $pivotKey2, $relatedKey = null, $relation = null)
```

The `BelongsToManySelf` is a concrete/child/sub-class of the Eloquent `BelongsToMany` class. So, All the methods available on the `BelongsToMany` is also available on this Relation.

Known Issues
------------

[](#known-issues)

The following Issues / Problems were found in this package or the underlying Database Engine.

- the `has` and `whereHas` constraint will not work in **MySQL &lt; v8.0.14**

Tips
----

[](#tips)

- To improve the performance of the relation, create **two Pivot Table indexes** such as `(pivot_key1, pivot_key2)` and `(pivot_key2, pivot_key1)`

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

[](#contributing)

Contributions are always welcome!

Feel free to open Issues and submit **Pull Requests**

You can also support me
[!["Buy Me A Coffee"](https://camo.githubusercontent.com/9f44ce2dc3b3eecdd02598900866ffc518801df1932849703dae1e5ce5031070/68747470733a2f2f7777772e6275796d6561636f666665652e636f6d2f6173736574732f696d672f637573746f6d5f696d616765732f6f72616e67655f696d672e706e67)](https://www.buymeacoffee.com/bgpratheep)

###  Health Score

53

—

FairBetter than 96% of packages

Maintenance74

Regular maintenance activity

Popularity43

Moderate usage in the ecosystem

Community13

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 93.2% 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 ~118 days

Recently: every ~72 days

Total

16

Last Release

136d ago

Major Versions

1.0.0 → 2.1.02021-05-28

1.x-dev → 2.1.22022-06-21

### Community

Maintainers

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

---

Top Contributors

[![kingmaker-agm](https://avatars.githubusercontent.com/u/23194965?v=4)](https://github.com/kingmaker-agm "kingmaker-agm (68 commits)")[![Bloemendaal](https://avatars.githubusercontent.com/u/1348606?v=4)](https://github.com/Bloemendaal "Bloemendaal (3 commits)")[![blite](https://avatars.githubusercontent.com/u/442226?v=4)](https://github.com/blite "blite (1 commits)")[![tobyzerner](https://avatars.githubusercontent.com/u/128862?v=4)](https://github.com/tobyzerner "tobyzerner (1 commits)")

---

Tags

laravelmany to manyrelationrelationshipbelongs-to-manymany-to-many-selfbelongs-to-many-selftwo way association

### Embed Badge

![Health badge](/badges/kingmaker-laravel-many-to-many-self-relationship/health.svg)

```
[![Health](https://phpackages.com/badges/kingmaker-laravel-many-to-many-self-relationship/health.svg)](https://phpackages.com/packages/kingmaker-laravel-many-to-many-self-relationship)
```

###  Alternatives

[spatie/laravel-medialibrary

Associate files with Eloquent models

6.2k45.4M705](/packages/spatie-laravel-medialibrary)[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

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

The Laravel magic applied to joins.

1.6k35.7M52](/packages/kirschbaum-development-eloquent-power-joins)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8723.3M27](/packages/yajra-laravel-oci8)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[glushkovds/phpclickhouse-laravel

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

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

PHPackages © 2026

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