<?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
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.