PHP code example of celinederoland / eloquent-polymorphic-model

1. Go to this page and download the library: Download celinederoland/eloquent-polymorphic-model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

celinederoland / eloquent-polymorphic-model example snippets


class Person extends Model {

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

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;
}

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

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');
    }
}

protected function polymorphismScopeIdentifier() {

    return 'polymorphism_scope_identifier';
}

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

public function setChildDefaultAttributes() {
      
     $this->gender = 'f';
}

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

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
  }
}