PHPackages                             pindab0ter/constrained-morph-to-for-laravel - 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. pindab0ter/constrained-morph-to-for-laravel

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

pindab0ter/constrained-morph-to-for-laravel
===========================================

Constrained polymorphic relationships for Laravel Eloquent - limit morphTo relationships to specific model types

v1.2.0(2mo ago)32.4k↓44%[1 PRs](https://github.com/pindab0ter/constrained-morph-to-for-laravel/pulls)MITPHPPHP ^8.2CI passing

Since Dec 9Pushed 1mo agoCompare

[ Source](https://github.com/pindab0ter/constrained-morph-to-for-laravel)[ Packagist](https://packagist.org/packages/pindab0ter/constrained-morph-to-for-laravel)[ Docs](https://github.com/pindab0ter/constrained-morph-to-for-laravel)[ GitHub Sponsors](https://github.com/pindab0ter)[ RSS](/packages/pindab0ter-constrained-morph-to-for-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (26)Versions (5)Used By (0)

Constrained MorphTo for Laravel
===============================

[](#constrained-morphto-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6a6362f4fb6510fb9824a6032783935bee2c78793220e5f95c0058e9fa0be245/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f70696e646162307465722f636f6e73747261696e65642d6d6f7270682d746f2d666f722d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pindab0ter/constrained-morph-to-for-laravel)[![GitHub Tests Action Status](https://camo.githubusercontent.com/875e496aefafac09c8e8f70b324f613a0387a5a23accf63f46db5d6c2e06e22f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70696e646162307465722f636f6e73747261696e65642d6d6f7270682d746f2d666f722d6c61726176656c2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/pindab0ter/constrained-morph-to-for-laravel/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/5e99e64c19cd0811c40bbd4c58c1cb03be6177586f6c989cfd5056ada3ac0010/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f70696e646162307465722f636f6e73747261696e65642d6d6f7270682d746f2d666f722d6c61726176656c2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/pindab0ter/constrained-morph-to-for-laravel/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/78d7980017e37471f90a90483f9c5a200f6104db6bb1eacd5a5c0dfb07a1ee03/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f70696e646162307465722f636f6e73747261696e65642d6d6f7270682d746f2d666f722d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pindab0ter/constrained-morph-to-for-laravel)

This package provides type-constrained polymorphic relationships for Laravel Eloquent. It extends Laravel’s `morphTo` relationship to only accept specific model types, ensuring data integrity and type safety for your polymorphic relations.

The Problem
-----------

[](#the-problem)

Laravel’s polymorphic relationships are flexible - a single relationship can relate to multiple model types. But sometimes you want the flexibility of a polymorphic database structure while enforcing that certain relationships only accept specific types:

```
// Standard Laravel morphTo - returns ANY model type
public function commentable()
{
    return $this->morphTo();
}

$comment->commentable; // Returns any model type
```

The Solution
------------

[](#the-solution)

This package lets you constrain polymorphic relationships to specific types:

```
use pindab0ter\ConstrainedMorphtoForLaravel\HasConstrainedMorphTo;

class Comment extends Model
{
    use HasConstrainedMorphTo;

    /** @return ConstrainedMorphTo */
    public function post()
    {
        return $this->constrainedMorphTo(Post::class, 'commentable_type', 'commentable_id');
    }

    /** @return ConstrainedMorphTo */
    public function commentable()
    {
        return $this->constrainedMorphTo(
            [Post::class, Video::class], // Accept multiple types
            'commentable_type',
            'commentable_id'
        );
    }
}

$comment->post; // Returns a Post if the type matches, null if it doesn't
$comment->commentable; // Returns a Post or Video if the type matches, null otherwise
```

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10.48+, 11.x, or 12.x

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

[](#installation)

Install the package via Composer:

```
composer require pindab0ter/constrained-morph-to-for-laravel
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

1. Add the `HasConstrainedMorphTo` trait to your model:

    ```
    use Illuminate\Database\Eloquent\Model;
    use pindab0ter\ConstrainedMorphtoForLaravel\HasConstrainedMorphTo;

    class Comment extends Model
    {
        use HasConstrainedMorphTo;

        /** @return ConstrainedMorphTo */
        public function commentable()
        {
            return $this->constrainedMorphTo(
                Post::class,        // Only allow Post models
                'commentable_type', // The type column name
                'commentable_id'    // The ID column name
            );
        }
    }
    ```
2. When the relationship type matches, it works like normal `morphTo`:

    ```
    $post = Post::create([...]);
    $comment = Comment::create([
        'commentable_id' => $post->id,
        'commentable_type' => Post::class,
    ]);

    $comment->commentable; // Returns the Post instance
    ```
3. When the type doesn't match the constraint, it returns `null`:

    ```
    $image = Image::create([...]);
    $comment = Comment::create([
        'commentable_id' => $image->id,
        'commentable_type' => Image::class, // Wrong type!
    ]);

    $comment->commentable; // Returns null (constraint not met)
    ```

### Multiple Allowed Types

[](#multiple-allowed-types)

You can allow multiple model types in a single relationship by passing an array:

```
/** @return ConstrainedMorphTo */
public function commentable()
{
    return $this->constrainedMorphTo(
        [Post::class, Video::class], // Accept both Post and Video models
        'commentable_type',
        'commentable_id'
    );
}
```

Now the relationship will accept either type:

```
$post = Post::create([...]);
$comment1 = Comment::create([
    'commentable_id' => $post->id,
    'commentable_type' => Post::class,
]);
$comment1->commentable; // Returns the Post instance

$video = Video::create([...]);
$comment2 = Comment::create([
    'commentable_id' => $video->id,
    'commentable_type' => Video::class,
]);
$comment2->commentable; // Returns the Video instance

$image = Image::create([...]);
$comment3 = Comment::create([
    'commentable_id' => $image->id,
    'commentable_type' => Image::class, // Not in allowed types!
]);
$comment3->commentable; // Returns null
```

### Advanced Usage

[](#advanced-usage)

You can optionally specify the relationship name and owner key:

```
public function commentable()
{
    return $this->constrainedMorphTo(
        Post::class,        // Constrained type (or array of types)
        'commentable_type', // Type column
        'commentable_id',   // ID column
        'commentable',      // Relationship name (optional)
        'id'                // Owner key (optional)
    );
}
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

License
-------

[](#license)

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

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance89

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 70% 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 ~49 days

Total

3

Last Release

61d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/034d7e1ec5ed815fb96f537a8bb911db8a50a4aa82be89d27a3e05db975fc185?d=identicon)[pindab0ter](/maintainers/pindab0ter)

---

Top Contributors

[![pindab0ter](https://avatars.githubusercontent.com/u/5128166?v=4)](https://github.com/pindab0ter "pindab0ter (7 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laraveldatabaseeloquentRelationshipspolymorphicmorphTo

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/pindab0ter-constrained-morph-to-for-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/pindab0ter-constrained-morph-to-for-laravel/health.svg)](https://phpackages.com/packages/pindab0ter-constrained-morph-to-for-laravel)
```

###  Alternatives

[indexzer0/eloquent-filtering

Powerful eloquent filtering

22425.9k3](/packages/indexzer0-eloquent-filtering)[msafadi/laravel-eloquent-join-with

Laravel Eloquent Join With Relationships

1646.0k](/packages/msafadi-laravel-eloquent-join-with)[moneo/laravel-morphmap

Custom morphMap support for Laravel Framework

521.6k](/packages/moneo-laravel-morphmap)

PHPackages © 2026

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