Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Mutembeijoe/0c83c91f2179bd693c8584144c068115 to your computer and use it in GitHub Desktop.

Select an option

Save Mutembeijoe/0c83c91f2179bd693c8584144c068115 to your computer and use it in GitHub Desktop.
Laravel Model Self Reference
<?php
namespace App\Traits;
trait SelfReferenceTrait
{
protected $parentColumn = 'parent_id';
public function parent()
{
return $this->belongsTo(static::class);
}
public function children()
{
return $this->hasMany(static::class, $this->parentColumn);
}
public function allChildren()
{
return $this->children()->with('allChildren');
}
public function root()
{
return $this->parent
? $this->parent->root()
: $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment