category hierarchy class in laravel code example

Example: get category hierarchy to the top laravel

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    // One level child
    public function child() {
        return $this->hasMany('App\Category', 'parent_category_id');
    }

    // Recursive children
    public function children() {
        return $this->hasMany('App\Category', 'parent_category_id')
          			->with('children');
    }

    // One level parent
    public function parent() {
        return $this->belongsTo('App\Category', 'parent_category_id');
    }

    // Recursive parents
    public function parents() {
        return $this->belongsTo('App\Category', 'parent_category_id')
          			->with('parent');
    }

}

Tags:

Php Example