PHPackages                             clickbar/laravel-custom-relations - 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. clickbar/laravel-custom-relations

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

clickbar/laravel-custom-relations
=================================

This package provides functionality for custom relations in laravel

1.0.1(2y ago)810[2 PRs](https://github.com/clickbar/laravel-custom-relations/pulls)MITPHPPHP ^8.1CI passing

Since Mar 22Pushed 7mo ago3 watchersCompare

[ Source](https://github.com/clickbar/laravel-custom-relations)[ Packagist](https://packagist.org/packages/clickbar/laravel-custom-relations)[ Docs](https://github.com/clickbar/laravel-power-relations)[ GitHub Sponsors](https://github.com/clickbar)[ RSS](/packages/clickbar-laravel-custom-relations/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (12)Versions (5)Used By (0)

Laravel Custom Relations
========================

[](#laravel-custom-relations)

[![Latest Version on Packagist](https://camo.githubusercontent.com/40dfb95d1f0c9cf40dac34696bf8ea8508184eb274f21ab16d897d87d31e74cd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636c69636b6261722f6c61726176656c2d637573746f6d2d72656c6174696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/clickbar/laravel-custom-relations)[![GitHub Tests Action Status](https://camo.githubusercontent.com/7ba5aac6c16003265ab5258990d06d367b6b3c3d1ff56730606a9a65c7e5ce74/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636c69636b6261722f6c61726176656c2d637573746f6d2d72656c6174696f6e732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/clickbar/laravel-custom-relations/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/27ba975c7de64acf857b585cc899f4c434d2f559edbb4cc3710a2a4f00905f29/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636c69636b6261722f6c61726176656c2d637573746f6d2d72656c6174696f6e732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/clickbar/laravel-custom-relations/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/90f0ab615901bcd402bd1b2873ab1c8ae6a3301a69512f57054988bbfdc153d5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636c69636b6261722f6c61726176656c2d637573746f6d2d72656c6174696f6e732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/clickbar/laravel-custom-relations)

Laravel provides some pretty good relations from scratch. If those relations do not fit the need, the community has provided a lot of other relation packages. Especially [staudenmeir](https://github.com/staudenmeir) did a lot if nice work on that end. However, in our projects we encountered the need of some really custom relations that could easily be expressed with an eloquent query, but not with default relations. Therefore, we created this package to give you the full control over your relations.

Introduction
------------

[](#introduction)

Sometimes it needs to be more custom. This package extends the default Laravel Relations with Relations that can be described by a query.

For explanation purposes we consider the following model with a simple concatenated relation use case. (for cases like this you should also have a look [eloquent-has-many-deep](https://github.com/staudenmeir/eloquent-has-many-deep) from staudenmeir). Even the example is quite simple, it should be able to represent the huge amount of possibilities that comes with custom relations. [![model chain](art/models.png)](art/models.png)

Let's explorer the connection between Client and Task in the default Laravel way:

```
$client = $task->order->project->client;
$tasks = $client->projects->flatMap(fn(Project $project) => $project->order->flatMap(fn(Order $order) => $order->tasks));
```

Wouldn't it be cool to do stuff like this with only 1 single database query?

```
$client = $task->client;
$tasks = $client->tasks;
```

With Custom Relations you can do this with only one single Database Query.

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

[](#installation)

You can install the package via composer:

```
composer require clickbar/laravel-custom-relations
```

Preparing the Model
-------------------

[](#preparing-the-model)

In order to use the Custom Relations, you must use the `HasCustomRelation` trait:

```
use Clickbar\LaravelCustomRelations\Traits\HasCustomRelation;

class Client extends Model{

    use HasCustomRelation;

    ...
}
```

Writing the Relation
--------------------

[](#writing-the-relation)

Like you know from Laravel, relations can return a collection of models or just one model. Therefore, this package has two Different Relations `CustomRelation` and `CustomRelationSingle`.

Let's look at our two examples from above:

```
class Task extends Model {

    use HasCustomRelation;

    public function client(): CustomRelationSingle {
        return $this->customRelationSingle(
            Client::class,
            function ($query) {
                $query
                    ->join('projects', 'clients.id', 'client_id')
                    ->join('orders', 'projects.id', 'project_id')
                    ->join('tasks', 'orders.id', 'order_id');
            },
        );
    }
}
```

```
class Client extends Model {

    use HasCustomRelation;

    public function tasks(): CustomRelation {
        return $this->customRelation(
            Task::class,
            function ($query) {
                $query
                    ->join('orders', 'orders.id', 'order_id')
                    ->join('projects', 'projects.id', 'project_id')
                    ->join('clients', 'clients.id', 'client_id');
            },
        );
    }
}
```

Like regular Laravel Relations, the query builder starts from the related model. This results in the following join chains:
$task-&gt;client: `Client->Projects->Orders->Tasks`
$client-&gt;tasks: `Tasks->Orders->Projects->Client`

If you prefer starting the join from the model the relation is defined on, you can use the method with the `fromParent` suffix:

```
class Task extends Model {

    use HasCustomRelation;

    public function client(): CustomRelationSingle {
        return $this->customRelationFromParentSingle(
            Client::class,
            function ($query) {
                $query
                    ->join('orders', 'orders.id', 'order_id')
                    ->join('projects', 'projects.id', 'project_id')
                    ->join('clients', 'clients.id', 'client_id');
            },
        );
    }
}
```

```
class Client extends Model {

    use HasCustomRelation;

    public function tasks(): CustomRelation {
        return $this->customRelationFromParent(
            Task::class,
            function ($query) {
                $query
                    ->join('projects', 'clients.id', 'client_id')
                    ->join('orders', 'projects.id', 'project_id')
                    ->join('tasks', 'orders.id', 'order_id');
            },
        );
    }
}
```

Limitations
-----------

[](#limitations)

Since the query might introduce a lot of joins, some methods known from Laravel Relations are not available:

- make
- create
- update
- forceCreate
- forceDelete

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)

- [Adrian Hawlitschek](https://github.com/53199186+ahawlitschek)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance44

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 59.1% 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 ~24 days

Total

2

Last Release

755d ago

### Community

Maintainers

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

---

Top Contributors

[![ahawlitschek](https://avatars.githubusercontent.com/u/53199186?v=4)](https://github.com/ahawlitschek "ahawlitschek (13 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")[![saibotk](https://avatars.githubusercontent.com/u/10776964?v=4)](https://github.com/saibotk "saibotk (4 commits)")[![studnitz](https://avatars.githubusercontent.com/u/9549394?v=4)](https://github.com/studnitz "studnitz (1 commits)")

---

Tags

eloquentlaravellaravel-packagephprelationshipslaravelclickbarlaravel-custom-relations

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/clickbar-laravel-custom-relations/health.svg)

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

###  Alternatives

[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spatie/laravel-model-flags

Add flags to Eloquent models

4301.1M1](/packages/spatie-laravel-model-flags)[spatie/laravel-sql-commenter

Add comments to SQL queries made by Laravel

1931.4M1](/packages/spatie-laravel-sql-commenter)[spatie/laravel-deleted-models

Automatically copy deleted records to a separate table

409109.8k4](/packages/spatie-laravel-deleted-models)[wnx/laravel-backup-restore

A package to restore database backups made with spatie/laravel-backup.

203330.1k2](/packages/wnx-laravel-backup-restore)

PHPackages © 2026

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