PHPackages                             celinederoland/eloquent-polymorphic-model - 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. celinederoland/eloquent-polymorphic-model

ActiveLibrary

celinederoland/eloquent-polymorphic-model
=========================================

Extend eloquent facilities to map one class Hierarchy branch to one table in database

2.0.3(7y ago)013PHPPHP 7.\*

Since Oct 20Pushed 7y ago1 watchersCompare

[ Source](https://github.com/celinederoland/eloquent-polymorphic-model)[ Packagist](https://packagist.org/packages/celinederoland/eloquent-polymorphic-model)[ RSS](/packages/celinederoland-eloquent-polymorphic-model/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (2)Versions (4)Used By (0)

Eloquent extension for polymorphic models
=========================================

[](#eloquent-extension-for-polymorphic-models)

Extend eloquent facilities to map one class Hierarchy branch to one table in database.

Purpose
-------

[](#purpose)

If you have one table on database (let say a `Person` table with fields `person_id`, `name` and `gender`) and you want to map it with your class hierarchy (let say a parent class `Person` and 2 childs `Man extends Person` and `Woman extends Person`), then you can use this package to make the mapping automatically.

Configure class mapping
-----------------------

[](#configure-class-mapping)

### Retrieving instances from the parent class

[](#retrieving-instances-from-the-parent-class)

In parent class, define the Model as usual :

```
class Person extends Model {

    protected $table      = 'Person';
    protected $primaryKey = 'person_id';

}
```

Define empty children classes :

```
class Man extends Person {}

class Woman extends Person {}

```

In parent class use the `EloquentPolymorphism\PolymorphicParent` helper You must define how database results will be bound with your class hierarchy (in my example it depends on the `gender` field value)

```
protected function instanceFactory($attributes) {

    if (!array_key_exists('gender', $attributes)) {
        return static::class;
    }

    switch ($attributes['gender']) {
        case self::TYPE_WOMAN:
            return Woman::class;
        case self::TYPE_MAN:
            return Man::class;
    }
    return static::class;
}
```

With that you can retrieve a collection of Men and Women :

```
$persons = Person::all(); //an eloquent collection, containing instances of `Man` and instances of `Woman`
```

### Retrieving instances from children classes

[](#retrieving-instances-from-children-classes)

Now we must define constraints in child classes (otherwise `Man::all()` would also retrieve a collection of men and women). For that in children classes you have to use the trait `EloquentPolymorphism\PolymorphicChild` and define the `polymorphismScope` constraint ;

```
class Man extends Person {

    * This scope will be added to all requests to make sure not retrieving other child.
     *
     * @param Builder $query
     */
    protected function polymorphismScope(Builder $query) {

        $query->where('gender', 'm');
    }
}
```

Now if you write `Man::all()` or any more complex query on `Man` model it will result on a collection of `Man` instances, corresponding to the table entries which represent men.

Optionally, you can overwrite the name of the scope you just defined in `Man` class adding this code either in parent or child class :

```
protected function polymorphismScopeIdentifier() {

    return 'polymorphism_scope_identifier';
}
```

Updating/Creating model :
-------------------------

[](#updatingcreating-model-)

### default attributes

[](#default-attributes)

It is strongly recommended to define default attributes values in children classes.

In our example it would be comfortable to write :

```
$woman = new Woman(['name' => 'Sandra']);
$woman->save();
```

without having to set her gender.

For this purpose, you must overwrite method `setChildDefaultAttributes` in children classes

```
public function setChildDefaultAttributes() {

     $this->gender = 'f';
}
```

### verifications on save method call

[](#verifications-on-save-method-call)

The trait `PolymorphicParent` prevents unnatural update/create on children like as example :

```
$man = new Man();
$man->gender = 'f';
$man->save(); //returns false, entry is not saved
```

This is done by checking that the conditions defined in `instanceFactory` method would effectively retrieve an instance of `Man`. You can overwrite this behaviour by implementing the method `checkHierarchyConstraintsBeforeSaving`

```
class Man extends Person {

  /**
   * @return bool
   */
  protected function checkHierarchyConstraintsBeforeSaving() {

      //Your logic : return true if it's correct to consider this instance as beeing a man, false otherwise
  }
}
```

Complex queries, relations, etc.
--------------------------------

[](#complex-queries-relations-etc)

You can use all other functionality of Eloquent models like usual. In particular, you can define relations and complex queries as needed.

Contribute
==========

[](#contribute)

Fork the project in your github account. Init gitflow

```
git flow init
git flow feature start feature-name develop
```

Composer install

```
sh composer.sh install
```

Test

```
docker-compose up testunit
```

Code

```
git push
```

Create a merge request from you're release branch to develop

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 90% 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

Unknown

Total

1

Last Release

2758d ago

### Community

Maintainers

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

---

Top Contributors

[![celinederoland-infomaniak](https://avatars.githubusercontent.com/u/79153135?v=4)](https://github.com/celinederoland-infomaniak "celinederoland-infomaniak (9 commits)")[![celinederoland](https://avatars.githubusercontent.com/u/6780152?v=4)](https://github.com/celinederoland "celinederoland (1 commits)")

---

Tags

eloquent-orm-modelspolymorphism

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/celinederoland-eloquent-polymorphic-model/health.svg)

```
[![Health](https://phpackages.com/badges/celinederoland-eloquent-polymorphic-model/health.svg)](https://phpackages.com/packages/celinederoland-eloquent-polymorphic-model)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[casbin/laravel-authz

An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

324339.9k4](/packages/casbin-laravel-authz)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

44643.1k1](/packages/pressbooks-pressbooks)[defstudio/pest-plugin-laravel-expectations

A plugin to add laravel tailored expectations to Pest

98548.9k4](/packages/defstudio-pest-plugin-laravel-expectations)

PHPackages © 2026

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