{"id":37006453,"url":"https://github.com/celinederoland/eloquent-polymorphic-model","last_synced_at":"2026-01-14T00:45:26.459Z","repository":{"id":62500622,"uuid":"153870554","full_name":"celinederoland/eloquent-polymorphic-model","owner":"celinederoland","description":"Extend eloquent facilities to map one class Hierarchy branch to one table in database","archived":false,"fork":false,"pushed_at":"2018-10-21T01:36:47.000Z","size":40,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-12-01T01:29:18.271Z","etag":null,"topics":["eloquent-orm-models","polymorphism"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/celinederoland.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-20T04:47:32.000Z","updated_at":"2018-10-20T14:15:21.000Z","dependencies_parsed_at":"2022-11-02T09:46:18.823Z","dependency_job_id":null,"html_url":"https://github.com/celinederoland/eloquent-polymorphic-model","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/celinederoland/eloquent-polymorphic-model","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/celinederoland%2Feloquent-polymorphic-model","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/celinederoland%2Feloquent-polymorphic-model/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/celinederoland%2Feloquent-polymorphic-model/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/celinederoland%2Feloquent-polymorphic-model/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/celinederoland","download_url":"https://codeload.github.com/celinederoland/eloquent-polymorphic-model/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/celinederoland%2Feloquent-polymorphic-model/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28406526,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T21:51:37.118Z","status":"ssl_error","status_checked_at":"2026-01-13T21:45:14.585Z","response_time":56,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["eloquent-orm-models","polymorphism"],"created_at":"2026-01-14T00:45:25.848Z","updated_at":"2026-01-14T00:45:26.452Z","avatar_url":"https://github.com/celinederoland.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Eloquent extension for polymorphic models\nExtend eloquent facilities to map one class Hierarchy branch to one table in database.\n\n## Purpose \nIf 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.\n\n## Configure class mapping \n\n### Retrieving instances from the parent class\n\nIn parent class, define the Model as usual :\n```php\nclass Person extends Model {\n\n    protected $table      = 'Person';\n    protected $primaryKey = 'person_id';\n    \n}\n```\n\nDefine empty children classes :\n\n```\nclass Man extends Person {}\n\nclass Woman extends Person {}\n```\n\nIn parent class use the `EloquentPolymorphism\\PolymorphicParent` helper\nYou must define how database results will be bound with your class hierarchy (in my example it depends on the `gender` field value)\n```php\nprotected function instanceFactory($attributes) {\n\n    if (!array_key_exists('gender', $attributes)) {\n        return static::class;\n    }\n\n    switch ($attributes['gender']) {\n        case self::TYPE_WOMAN:\n            return Woman::class;\n        case self::TYPE_MAN:\n            return Man::class;\n    }\n    return static::class;\n}\n```\n\nWith that you can retrieve a collection of Men and Women :\n```php\n$persons = Person::all(); //an eloquent collection, containing instances of `Man` and instances of `Woman`\n```\n\n### Retrieving instances from children classes\n\nNow we must define constraints in child classes (otherwise `Man::all()` would also retrieve a collection of men and women).\nFor that in children classes you have to use the trait `EloquentPolymorphism\\PolymorphicChild` and define the `polymorphismScope` constraint ;\n\n```php\nclass Man extends Person {\n\n    * This scope will be added to all requests to make sure not retrieving other child.\n     *\n     * @param Builder $query\n     */\n    protected function polymorphismScope(Builder $query) {\n    \n        $query-\u003ewhere('gender', 'm');\n    }\n}\n``` \n\nNow 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.\n\nOptionally, you can overwrite the name of the scope you just defined in `Man` class adding this code either in parent or child class :\n\n```php\nprotected function polymorphismScopeIdentifier() {\n\n    return 'polymorphism_scope_identifier';\n}\n```\n\n\n## Updating/Creating model :\n\n### default attributes\n\nIt is strongly recommended to define default attributes values in children classes. \n\nIn our example it would be comfortable to write : \n```php\n$woman = new Woman(['name' =\u003e 'Sandra']); \n$woman-\u003esave();\n``` \nwithout having to set her gender. \n\nFor this purpose, you must overwrite method `setChildDefaultAttributes` in children classes\n\n```php\npublic function setChildDefaultAttributes() {\n      \n     $this-\u003egender = 'f';\n}\n```\n\n### verifications on save method call\n\nThe trait `PolymorphicParent` prevents unnatural update/create on children like as example :\n\n```php\n$man = new Man();\n$man-\u003egender = 'f';\n$man-\u003esave(); //returns false, entry is not saved\n```\n\nThis is done by checking that the conditions defined in `instanceFactory` method would effectively retrieve an instance of `Man`.\nYou can overwrite this behaviour by implementing the method `checkHierarchyConstraintsBeforeSaving` \n\n```php\nclass Man extends Person {\n  \n  /**\n   * @return bool\n   */\n  protected function checkHierarchyConstraintsBeforeSaving() {\n  \n      //Your logic : return true if it's correct to consider this instance as beeing a man, false otherwise\n  }\n}\n```\n\n## Complex queries, relations, etc.\n\nYou can use all other functionality of Eloquent models like usual. In particular, you can define relations and complex queries as needed.\n\n# Contribute\n\nFork the project in your github account. Init gitflow\n```bash\ngit flow init\ngit flow feature start feature-name develop\n```\n\nComposer install\n````bash\nsh composer.sh install\n````\n\nTest\n```bash\ndocker-compose up testunit\n```\n\nCode\n\n```bash\ngit push\n```\n\nCreate a merge request from you're release branch to develop\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcelinederoland%2Feloquent-polymorphic-model","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcelinederoland%2Feloquent-polymorphic-model","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcelinederoland%2Feloquent-polymorphic-model/lists"}