Because I am eager loading all of these categories and pages in the first palce using the following line of code and my Categories model:
$categories = Category::with( 'childrenRecursive' )->whereNull( 'parent_id' )->get();
I was able to use a recursive formula to sum up the number of pages underneath each category without slowing down the page:
foreach( $categories as $category ) {
$category->pagesCount = 0;
$category->pagesCount += $category->pages->count();
foreach( $category->childrenRecursive as $child ) {
$category->pagesCount += countChildPages( $child );
}
}
function countChildPages( $category ) {
$category->pagesCount = 0;
$category->pagesCount += $category->pages->count();
foreach( $category->childrenRecursive as $child ) {
$category->pagesCount += countChildPages( $child );
}
return $category->pagesCount;
}
I then just accessed the count ($category->pagesCount) whenever I needed to use it on the page.
Example of sitemap.html page:
foreach( $categories as $category ) {
$category->pagesCount = 0;
$category->pagesCount += $category->pages->count();
foreach( $category->childrenRecursive as $child ) {
$category->pagesCount += countChildPages( $child );
}
}
foreach( $categories as $category ) {
if( $category->pagesCount > 0 ) {
echo '<div class="category">';
echo '<h2><a href="https://example.com/' . $category->slug . '">' . $category->name . ' (' . $category->pagesCount . ')</a></h2>';
foreach( $category->pages as $page ) {
showPage( $page );
}
foreach( $category->childrenRecursive as $child ) {
showSubCategory( $child );
}
echo '</div>';
}
}
function countChildPages( $category ) {
$category->pagesCount = 0;
$category->pagesCount += $category->pages->count();
foreach( $category->childrenRecursive as $child ) {
$category->pagesCount += countChildPages( $child );
}
return $category->pagesCount;
}
function showSubCategory( $category ) {
if( $category->pagesCount > 0 ) {
echo '<div class="category">';
echo '<h2><a href="https://example.com/' . $category->slug . '">' . $category->name . ' (' . $category->pagesCount . ')</a></h2>';
foreach( $category->pages as $page ) {
showPage( $page );
}
foreach( $category->childrenRecursive as $child ) {
showSubCategory( $child );
}
echo '</div>';
}
}
function showPage( $page ) {
echo '<div class="category page">';
echo '<h2><a href="https://example.com/' . $page->slug . '">' . $page->title . '</a></h2>';
echo '</div>';
}