Getting Started
Ancestry provides closure table hierarchies for Eloquent models with O(1) ancestor/descendant queries. This guide will help you get started quickly.
Installation
Section titled “Installation”composer require cline/ancestryPublish Configuration
Section titled “Publish Configuration”php artisan vendor:publish --tag=ancestry-configRun Migrations
Section titled “Run Migrations”php artisan migrateBasic Setup
Section titled “Basic Setup”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;}Quick Example
Section titled “Quick Example”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 hierarchyAncestry::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: 3Using the Fluent API
Section titled “Using the Fluent API”// Using the for() conductorAncestry::for($seller) ->type('seller') ->ancestors();
// Using the ofType() conductorAncestry::ofType('seller') ->roots();Using the Trait Methods
Section titled “Using the Trait Methods”// Using trait methods directly on the model$seller->addToAncestry('seller', $manager);$seller->getAncestryAncestors('seller');$seller->isAncestryDescendantOf($ceo, 'seller');Next Steps
Section titled “Next Steps”- Basic Usage - Learn the core operations
- Fluent API - Master the chainable interface
- Configuration - Customize Ancestry for your needs
- Multiple Ancestor Types - Manage different hierarchies