PHPackages                             tranghaviet/laravel-custom-relation - 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. tranghaviet/laravel-custom-relation

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

tranghaviet/laravel-custom-relation
===================================

A custom relation for when stock relations aren't enough.

v0.0.6(4y ago)05MITPHPPHP &gt;=7.1

Since Aug 30Pushed 4y agoCompare

[ Source](https://github.com/tranghaviet/laravel-custom-relation)[ Packagist](https://packagist.org/packages/tranghaviet/laravel-custom-relation)[ Docs](https://github.com/tranghaviet/laravel-custom-relation)[ RSS](/packages/tranghaviet-laravel-custom-relation/feed)WikiDiscussions master Synced 1mo ago

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

Laravel Custom Relation
=======================

[](#laravel-custom-relation)

A custom relation for when stock relations aren't enough.

Use this if...
--------------

[](#use-this-if)

- None of the stock Relations fit the bill. (BelongsToManyThrough, etc)

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

[](#installation)

The recommended way to install is with [composer](http://getcomposer.org/):

```
composer require tranghaviet/laravel-custom-relation
```

Example
-------

[](#example)

Let's say we have 3 models:

- `User`
- `Role`
- `Permission`

Let's also say `User` has a many-to-many relation with `Role`, and `Role` has a many-to-many relation with `Permission`.

So their models might look something like this. (I kept them brief on purpose.)

```
class User
{
    public function roles() {
        return $this->belongsToMany(Role::class);
    }
}
```

```
class Role
{
    public function users() {
        return $this->belongsToMany(User::class);
    }

    public function permissions() {
        return $this->belongsToMany(Permission::class);
    }
}
```

```
class Permission
{
    public function roles() {
        return $this->belongsToMany(Role::class);
    }
}
```

**What if you wanted to get all the `Permission`s for a `User`, or all the `User`s with a particular `Permission`?** There no stock Relation in Laravel to descibe this. What we need is a `BelongsToManyThrough` but no such thing exists in stock Laravel.

Solution
--------

[](#solution)

First, make sure your models are using the `HasCustomRelations` trait. Then, define custom relations like this.

```
use LaravelCustomRelation\HasCustomRelations;

class User
{
    use HasCustomRelations;

    /**
     * Get the related permissions
     *
     * @return Illuminate\Database\Eloquent\Relations\Relation
     */
    public function permissions()
    {
        return $this->custom(
            Permission::class,

            // add constraints
            function ($relation) {
                $relation->getQuery()
                    // join the pivot table for permission and roles
                    ->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id')
                    // join the pivot table for users and roles
                    ->join('role_user', 'role_user.role_id', '=', 'permission_role.role_id')
                    // for this user
                    ->where('role_user.user_id', $this->id);
            },

            // add eager constraints
            function ($relation, $models) {
                $relation->getQuery()->whereIn('role_user.user_id', $relation->getKeys($models));
            }
        );
    }
}
```

```
use LaravelCustomRelation\HasCustomRelations;

class Permission
{
    use HasCustomRelations;

    /**
     * Get the related users
     *
     * @return Illuminate\Database\Eloquent\Relations\Relation
     */
    public function users()
    {
        return $this->custom(
            User::class,

            // constraints
            function ($relation) {
                $relation->getQuery()
                    // join the pivot table for users and roles
                    ->join('role_user', 'role_user.user_id', '=', 'users.id')
                    // join the pivot table for permission and roles
                    ->join('permission_role', 'permission_role.role_id', '=', 'role_user.role_id')
                    // for this permission
                    ->where('permission_role.permission_id', $this->id);
            },

            // eager constraints
            function ($relation, $models) {
                $relation->getQuery()->whereIn('permission_role.permission_id', $relation->getKeys($models));
            }
        );
    }
}
```

You could now do all the normal stuff for relations without having to query in-between relations first.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% 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 ~365 days

Recently: every ~456 days

Total

6

Last Release

1718d ago

PHP version history (2 changes)0.0.1PHP &gt;=5.6.4

0.0.4PHP &gt;=7.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/23404016?v=4)[Ha Viet Trang](/maintainers/tranghaviet)[@tranghaviet](https://github.com/tranghaviet)

---

Top Contributors

[![johnnyfreeman](https://avatars.githubusercontent.com/u/371481?v=4)](https://github.com/johnnyfreeman "johnnyfreeman (12 commits)")[![aaronlord](https://avatars.githubusercontent.com/u/1591606?v=4)](https://github.com/aaronlord "aaronlord (2 commits)")[![tranghaviet](https://avatars.githubusercontent.com/u/23404016?v=4)](https://github.com/tranghaviet "tranghaviet (2 commits)")[![danielmorgan](https://avatars.githubusercontent.com/u/530996?v=4)](https://github.com/danielmorgan "danielmorgan (1 commits)")[![HosseyNJF](https://avatars.githubusercontent.com/u/18368279?v=4)](https://github.com/HosseyNJF "HosseyNJF (1 commits)")[![LoveMHz](https://avatars.githubusercontent.com/u/1701315?v=4)](https://github.com/LoveMHz "LoveMHz (1 commits)")[![nerdo](https://avatars.githubusercontent.com/u/1031502?v=4)](https://github.com/nerdo "nerdo (1 commits)")

---

Tags

laraveleloquentrelationrelationship

### Embed Badge

![Health badge](/badges/tranghaviet-laravel-custom-relation/health.svg)

```
[![Health](https://phpackages.com/badges/tranghaviet-laravel-custom-relation/health.svg)](https://phpackages.com/packages/tranghaviet-laravel-custom-relation)
```

###  Alternatives

[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[bavix/laravel-clickhouse

Eloquent model for ClickHouse

72214.1k2](/packages/bavix-laravel-clickhouse)[reedware/laravel-composite-relations

Adds the ability define composite eloquent relations.

17131.3k](/packages/reedware-laravel-composite-relations)[stayallive/laravel-eloquent-observable

Register Eloquent model event listeners just-in-time directly from the model.

2928.9k7](/packages/stayallive-laravel-eloquent-observable)[codenco-dev/eloquent-model-tester

Test easier your Eloquent Models in your Laravel Project

208.3k1](/packages/codenco-dev-eloquent-model-tester)

PHPackages © 2026

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