Skip to content

Getting Started

Ancestry provides closure table hierarchies for Eloquent models with O(1) ancestor/descendant queries. This guide will help you get started quickly.

Terminal window
composer require cline/ancestry
Terminal window
php artisan vendor:publish --tag=ancestry-config
Terminal window
php artisan migrate

Add the HasAncestry trait to any model that needs hierarchical relationships:

<?php
namespace App\Models;
use Cline\Ancestry\Concerns\HasAncestry;
use Illuminate\Database\Eloquent\Model;
class Seller extends Model
{
use HasAncestry;
}
use App\Models\Seller;
use Cline\Ancestry\Facades\Ancestry;
// Create a hierarchy
$ceo = Seller::create(['name' => 'CEO']);
$vp = Seller::create(['name' => 'VP of Sales']);
$manager = Seller::create(['name' => 'Regional Manager']);
$seller = Seller::create(['name' => 'Sales Rep']);
// Build the hierarchy
Ancestry::addToAncestry($ceo, 'seller');
Ancestry::addToAncestry($vp, 'seller', $ceo);
Ancestry::addToAncestry($manager, 'seller', $vp);
Ancestry::addToAncestry($seller, 'seller', $manager);
// Query the hierarchy
$ancestors = Ancestry::getAncestors($seller, 'seller');
// Returns: [Regional Manager, VP of Sales, CEO]
$descendants = Ancestry::getDescendants($ceo, 'seller');
// Returns: [VP of Sales, Regional Manager, Sales Rep]
$depth = Ancestry::getDepth($seller, 'seller');
// Returns: 3
// Using the for() conductor
Ancestry::for($seller)
->type('seller')
->ancestors();
// Using the ofType() conductor
Ancestry::ofType('seller')
->roots();
// Using trait methods directly on the model
$seller->addToAncestry('seller', $manager);
$seller->getAncestryAncestors('seller');
$seller->isAncestryDescendantOf($ceo, 'seller');