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

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

johnnyfreeman/laravel-custom-relation
=====================================

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

0.0.3(9y ago)6924.0k25[4 issues](https://github.com/johnnyfreeman/laravel-custom-relation/issues)MITPHPPHP &gt;=5.6.4

Since Aug 30Pushed 5y ago1 watchersCompare

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

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

> This repo was a bit of a science experiment to find a solution to [this issue](https://stackoverflow.com/questions/39213022/custom-laravel-relations). I now believe a better to handle custom relations is to create a new class possibly extending one of the existing classes.

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 johnnyfreeman/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

33

—

LowBetter than 72% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 76.5% 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 ~2 days

Total

3

Last Release

3586d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/39a98101c956c920ec10cbe9d809eb1e8904303ac7ab252cc9a8a6953065dbae?d=identicon)[johnnyfreeman](/maintainers/johnnyfreeman)

---

Top Contributors

[![johnnyfreeman](https://avatars.githubusercontent.com/u/371481?v=4)](https://github.com/johnnyfreeman "johnnyfreeman (13 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

laravellaraveleloquentrelationrelationship

### Embed Badge

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

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

###  Alternatives

[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11222.5M33](/packages/anourvalar-eloquent-serialize)[waad/laravel-model-metadata

A robust Laravel package for handling metadata with JSON casting, custom relation names, and advanced querying capabilities.

854.1k](/packages/waad-laravel-model-metadata)[mozex/laravel-scout-bulk-actions

Import, flush, and queue-import all your Laravel Scout searchable models at once. Auto-discovers models, runs in bulk, tracks progress.

1437.7k](/packages/mozex-laravel-scout-bulk-actions)[binafy/laravel-reactions

React to something in Laravel framework

875.6k](/packages/binafy-laravel-reactions)

PHPackages © 2026

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