Skip to content

Instantly share code, notes, and snippets.

@danharper
Created January 23, 2014 11:51
Show Gist options
  • Save danharper/8577330 to your computer and use it in GitHub Desktop.
Save danharper/8577330 to your computer and use it in GitHub Desktop.
Laravel/Eloquent Single Table Inheritance Trait
<?php
class Category extends Eloquent {
use EloquentSingleTableInheritenceTrait;
protected function singleTableInheritanceMpa()
{
return [
1 => 'InventoryCategory',
2 => 'PhotoCategory',
3 => 'BrochureCategory',
];
}
}
class InventoryCategory extends Category {
}
class PhotoCategory extends Category {
}
class BrochureCategory extends Category {
}
// usage:
$product->category_id; // 1
$product->category; // InventoryCategory
// EloquentSingleTableInheritenceTrait.php
<?php
trait EloquentSingleTableInheritenceTrait {
protected function singleTableInheritanceKey()
{
return 'id';
}
protected function singleTableInheritanceMap()
{
return [];
}
public function newFromBuilder($attributes = array())
{
$inheritanceKey = $this->singleTableInheritanceKey();
$inheritanceMap = $this->singleTableInheritanceMap();
$key = $attributes->$inheritanceKey;
if (array_key_exists($key, $inheritanceMap))
{
$instance = (new $inheritanceMap[$key])->newInstance([], true);
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
return parent::newFromBuilder($attributes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment