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

Category:

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');
}

Controller:

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

blade.php

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

Source: Laravel

Leave a Reply