Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A model trait that allows child models to use parent table names and relationship keys.
namespace App\Abilities;
use Illuminate\Support\Str;
use ReflectionClass;
* Note: This is a preview of an upcoming package from Tighten.
trait HasParentModel
public function getParentClass()
static $parentClassName;
return $parentClassName ?: $parentClassName = (new ReflectionClass($this))->getParentClass()->getName();
public function getTable()
if (! isset($this->table)) {
return str_replace('\\', '', Str::snake(Str::plural(class_basename($this->getParentClass()))));
return $this->table;
public function getForeignKey()
return Str::snake(class_basename($this->getParentClass())).'_'.$this->primaryKey;
public function joiningTable($related)
$models = [
return strtolower(implode('_', $models));

deleugpn commented Sep 9, 2017

You rock, man. Anxiously waiting to see this package.

tucq88 commented Sep 13, 2017

Awesome! Much convenient on real-life problem. Can't wait until it released.

Excellent approach. Waiting for final release.

shigg1120 commented Oct 5, 2017

When is the package gonna be released? I am dying to use it ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment