Filter by subpages

Hey there,
I want to use filterBy() (or whatever works) on a $pages collection to filter out only those pages who have a specific subpage (eg same uid()).

Say, I got some page’s children who themselves have year-based subpages: Page cats has children alice and bob. alice has subpages games and food, bob has subpages food and drinks. I want to filter cats's children by subpage games.

How to get all children of cats who have a specific subpage (not the subpages themselves)?

You can use the filter($callback) method to achieve things like this:

<?php

$catChildren = page('cats')->children();
$catsWithGameGrandchildren = $catChildren->filter(function($child) {
  return $child->children()->findBy('uid', 'games');
});

dump($catsWithGameGrandchildren);

?>
1 Like

Good lord that’s just great! Thank you!

One thing though: How can I pass a variable from the outside in there? When trying to substitute return $child->children()->findBy('uid', 'games') with return $child->children()->findBy('uid', $some-variable)an error pops, saying $some-variable isn’t defined.

This is a scoping issue with PHP—if you’re familiar with JavaScript, this will grind your gears:

# Note the "use" keyword before the function block:
$catsWithGameGrandchildren = $catChildren->filter(function($child) use ($mySearchVar) {
  return $child->children()->findBy('uid', $mySearchVar);
});

…basically, you have to manually expose variables to anonymous functions defined in a given scope.

Hope this helps!