PHPackages                             staudenmeir/laravel-merged-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. staudenmeir/laravel-merged-relations

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

staudenmeir/laravel-merged-relations
====================================

Merged Laravel Eloquent relationships

v1.10(1y ago)186209.3k—1.8%11[1 issues](https://github.com/staudenmeir/laravel-merged-relations/issues)MITPHPPHP ^8.2CI passing

Since Jun 23Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/staudenmeir/laravel-merged-relations)[ Packagist](https://packagist.org/packages/staudenmeir/laravel-merged-relations)[ Fund](https://paypal.me/JonasStaudenmeir)[ RSS](/packages/staudenmeir-laravel-merged-relations/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (31)Used By (0)

Laravel Merged Relations
========================

[](#laravel-merged-relations)

[![CI](https://github.com/staudenmeir/laravel-merged-relations/actions/workflows/ci.yml/badge.svg)](https://github.com/staudenmeir/laravel-merged-relations/actions/workflows/ci.yml?query=branch%3Amain)[![Code Coverage](https://camo.githubusercontent.com/707ad3235df469d5c0aba088f314321f629bed9b0f70967f976caff26b922af3/68747470733a2f2f636f6465636f762e696f2f67682f7374617564656e6d6569722f6c61726176656c2d6d65726765642d72656c6174696f6e732f67726170682f62616467652e7376673f746f6b656e3d5a525947443434515658)](https://codecov.io/gh/staudenmeir/laravel-merged-relations)[![PHPStan](https://camo.githubusercontent.com/2b1732baa25914ee5ccbeaf42980d671de29700b49e0639e1edc8e66181f6905/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c25323031302d627269676874677265656e2e7376673f7374796c653d666c6174)](https://github.com/staudenmeir/laravel-merged-relations/actions/workflows/static-analysis.yml?query=branch%3Amain)[![Latest Stable Version](https://camo.githubusercontent.com/ac0295022d61948566ede5f4e5651e331dcf580982a157fc39b03d1b03de9aab/68747470733a2f2f706f7365722e707567782e6f72672f7374617564656e6d6569722f6c61726176656c2d6d65726765642d72656c6174696f6e732f762f737461626c65)](https://packagist.org/packages/staudenmeir/laravel-merged-relations)[![Total Downloads](https://camo.githubusercontent.com/771e7f553aeb7e9dc56231cc97df02cedb645680a541338333237081d71cb5e4/68747470733a2f2f706f7365722e707567782e6f72672f7374617564656e6d6569722f6c61726176656c2d6d65726765642d72656c6174696f6e732f646f776e6c6f616473)](https://packagist.org/packages/staudenmeir/laravel-merged-relations/stats)[![License](https://camo.githubusercontent.com/70a6c08a3a5b2efc2bf2c19dab5cadcebce64b23d83aca9b20ad34ccd3d773f1/68747470733a2f2f706f7365722e707567782e6f72672f7374617564656e6d6569722f6c61726176656c2d6d65726765642d72656c6174696f6e732f6c6963656e7365)](https://github.com/staudenmeir/laravel-merged-relations/blob/main/LICENSE)

This Laravel Eloquent extension allows merging multiple relationships using SQL views.
The relationships can target the same or different related models.

Supports Laravel 5.5+.

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

[](#installation)

```
composer require staudenmeir/laravel-merged-relations:"^1.0"

```

Use this command if you are in PowerShell on Windows (e.g. in VS Code):

```
composer require staudenmeir/laravel-merged-relations:"^^^^1.0"

```

Versions
--------

[](#versions)

LaravelPackage13.x1.1112.x1.1011.x1.910.x1.69.x1.58.x1.47.x1.36.x1.25.81.15.5–5.71.0Usage
-----

[](#usage)

- [Use Cases](#use-cases)
- [Step 1: Creating Views](#step-1-creating-views)
- [Step 2: Defining Relationships](#step-2-defining-relationships)
- [Pivot Table Data](#pivot-table-data)
- [Limitations](#limitations)
- [Testing](#testing)

### Use Cases

[](#use-cases)

Use the package to merge multiple polymorphic relationships:

```
class Tag extends Model
{
    public function allTaggables()
    {
        // TODO
    }

    public function posts()
    {
        return $this->morphedByMany(Post::class, 'taggable');
    }

    public function videos()
    {
        return $this->morphedByMany(Video::class, 'taggable');
    }
}
```

Or use it to merge relationships with different depths:

```
class User extends Model
{
    public function allComments()
    {
        // TODO
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function postComments()
    {
        return $this->hasManyThrough(Comment::class, Post::class);
    }
}
```

### Step 1: Creating Views

[](#step-1-creating-views)

Before you can define the new relationship, you need to create the merge view in a migration:

```
use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'all_taggables',
    [(new Tag)->posts(), (new Tag)->videos()]
);
```

By default, the view doesn't remove duplicates. Use `createMergeViewWithoutDuplicates()` to get unique results:

```
use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeViewWithoutDuplicates(
    'all_comments',
    [(new User)->comments(), (new User)->postComments()]
);
```

You can also replace an existing view:

```
use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createOrReplaceMergeView(
    'all_comments',
    [(new User)->comments(), (new User)->postComments()]
);
```

The package includes [staudenmeir/laravel-migration-views](https://github.com/staudenmeir/laravel-migration-views). You can use its methods to rename and drop views:

```
use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::renameView('all_comments', 'user_comments');

Schema::dropView('all_comments');
```

If you are using `php artisan migrate:fresh`, you can drop all views with `--drop-views`.

### Step 2: Defining Relationships

[](#step-2-defining-relationships)

With the view created, you can define the merged relationship.

Use the `HasMergedRelationships` trait in your model and provide the view name:

```
class Tag extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function allTaggables(): \Staudenmeir\LaravelMergedRelations\Eloquent\Relations\MergedRelation
    {
        return $this->mergedRelation('all_taggables');
    }
}
```

If all original relationships target the same related model, you can use `mergedRelationWithModel()`. This allows you to access local scopes and use methods like `whereHas()` or `withCount()`:

```
class User extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function allComments(): \Staudenmeir\LaravelMergedRelations\Eloquent\Relations\MergedRelation
    {
        return $this->mergedRelationWithModel(Comment::class, 'all_comments');
    }
}
```

You can use the merged relationship like any other relationship:

```
$taggables = Tag::find($id)->allTaggables()->latest()->paginate();

$users = User::with('allComments')->get();
```

### Pivot Table Data

[](#pivot-table-data)

You can retrieve additional pivot columns if your merge view consists of many-to-many relationships.

Add the desired pivot columns to *all* relationships:

```
use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'all_taggables',
    [
        (new Tag)->posts()->withPivot('tagged_at'),
        (new Tag)->videos()->withPivot('tagged_at'),
    ]
);

$taggables = Tag::find($id)->allTaggables;

foreach ($taggables as $taggable) {
    dump($taggable->pivot->tagged_at);
}
```

### Limitations

[](#limitations)

In the original relationships, it's currently not possible to limit the selected columns or apply `withCount()`.

In the merged relationships, it's not possible to remove global scopes like `SoftDeletes`. They can only be removed in the original relationships.

### Testing

[](#testing)

If you use PHPUnit or a similar tool to run tests, add this property to your base test class to ensure that database views are dropped when the test database is cleaned up:

```
protected bool $dropViews = true;
```

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

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) and [CODE OF CONDUCT](.github/CODE_OF_CONDUCT.md) for details.

###  Health Score

59

—

FairBetter than 99% of packages

Maintenance66

Regular maintenance activity

Popularity51

Moderate usage in the ecosystem

Community14

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 99% 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 ~87 days

Recently: every ~120 days

Total

29

Last Release

78d ago

Major Versions

v1.10 → 8.5.x-dev2026-03-01

PHP version history (10 changes)1.0.x-devPHP &gt;=7.0

v1.1PHP ^7.1.3

v1.2PHP ^7.2

v1.3PHP ^7.2.5

v1.4PHP ^7.3

v1.4.1PHP ^7.3|^8.0

v1.5PHP ^8.0.2

v1.6PHP ^8.1

v1.9PHP ^8.2

8.5.x-devPHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/3c1c3cda28d147c1899037c3187f89a606ca14f51190de59e88fa91e51647ff6?d=identicon)[staudenmeir](/maintainers/staudenmeir)

---

Top Contributors

[![staudenmeir](https://avatars.githubusercontent.com/u/1853169?v=4)](https://github.com/staudenmeir "staudenmeir (102 commits)")[![ChrisHardie](https://avatars.githubusercontent.com/u/311772?v=4)](https://github.com/ChrisHardie "ChrisHardie (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/staudenmeir-laravel-merged-relations/health.svg)

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

###  Alternatives

[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[staudenmeir/eloquent-json-relations

Laravel Eloquent relationships with JSON keys

1.1k5.8M24](/packages/staudenmeir-eloquent-json-relations)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.1M11](/packages/bavix-laravel-wallet)[dragon-code/migrate-db

Easy data transfer from one database to another

15717.4k](/packages/dragon-code-migrate-db)[gearbox-solutions/eloquent-filemaker

A package for getting FileMaker records as Eloquent models in Laravel

6454.8k2](/packages/gearbox-solutions-eloquent-filemaker)[cybercog/laravel-ownership

Laravel Ownership simplify management of Eloquent model's owner.

9126.6k3](/packages/cybercog-laravel-ownership)

PHPackages © 2026

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