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

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

ardalanamini/laravel-custom-relation
====================================

Create your own custom relation for when stock relations aren't enough

v0.1.5(2y ago)41714MITPHPPHP &gt;=7.0.0

Since Jan 3Pushed 2y ago1 watchersCompare

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

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

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

[](#laravel-custom-relation)

Create your own custom relation for when stock relations aren't enough

\[TOC\]

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 ardalanamini/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',
                  collect($models)->map(function ($value) {
                      return $value->getKey();
                  })->values()->unique()->sort()->all()
               );
            }
        );
    }
}
```

```
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',
                    collect($models)->map(function ($value) {
                        return $value->getKey();
                    })->values()->unique()->sort()->all()
                );
            }
        );
    }
}
```

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

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

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

Recently: every ~520 days

Total

6

Last Release

969d ago

### Community

Maintainers

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

---

Top Contributors

[![Dylan-DPC](https://avatars.githubusercontent.com/u/99973273?v=4)](https://github.com/Dylan-DPC "Dylan-DPC (1 commits)")[![johnpbloch](https://avatars.githubusercontent.com/u/446833?v=4)](https://github.com/johnpbloch "johnpbloch (1 commits)")[![yekta-kalantary](https://avatars.githubusercontent.com/u/26902978?v=4)](https://github.com/yekta-kalantary "yekta-kalantary (1 commits)")

---

Tags

customeloquentlaravelrelationrelationshiplaraveleloquentrelationcustomrelationship

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/ardalanamini-laravel-custom-relation/health.svg)](https://phpackages.com/packages/ardalanamini-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)[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)
