Unlimited Nested Categories not working, Method IlluminateDatabaseEloquentCollection::childrenRecursive does not exist

  laravel, recursion

I tried @foreach $categories->children() aswell in index, still gives the same error which is Method IlluminateDatabaseEloquentCollection::childrenRecursive does not exist, whichever function i use i get the same error, I want to display all the categories and their subcategories. Do not seem to figure out how


public function parent()
    return $this->belongsTo(Category::class, 'cat_id');
public function children()
    return $this->hasMany(Category::class, 'cat_id');
public function childrenRecursive()
   return $this->children()->with('childrenRecursive');


 public function index()
    $categories = Category::with('childrenRecursive')->whereNull('cat_id')->get();  
    return view('categories.index',compact('categories'));


@foreach ($categories->childrenRecursive() as $category)
                    <td data-cat-id="{{$category->id}}">
                        <!-- Button trigger modal -->
                        <button type="button" class="btn btn-primary add-subcat-modal-trigger">
                            Add Subcategory
                        <!-- Modal -->
                        <form action="{{route('categories.destroy',$category->id)}}" method="POST">
                            <button class="btn btn-danger">Delete</button>

Source: Laravel

Leave a Reply