n-level category (self reference relation)

Posted 3 weeks ago by mhdmirzaie

Hi Everyone,

I want to create n-level nested category, I have defined category table and define relations as below, it works but return only root categories plus its first level children.

// Category Model

class Category extends Model { protected $table = 'dms_category';

protected $guarded = ['id', 'created_at', 'updated_at'];

public function documents(){
    return $this->hasMany(Document::class);
}

public function children(){
    return $this->hasMany(Category::class, 'parent_id');
}

public function parent(){
    return $this->belongsTo(Category::class, 'parent_id');
}

} //CategoryController

public function index() {

    $categories = Category::whereParentId(0)->with( 'children')->paginate();

    return CategoryResource::collection($categories);
}

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.