0

I want to loop through database fields till I find the mother of all children. When I echo the $page->id in the findMother() function (instead of returning it) it gives me the correct page id, but it doesn't return it to the second function.

private function findMother($id) {
    $page = Page::find($id);
    if($page->parent_id != 0 || $page->parent_id != null) {
        $this->findMother($page->parent_id);
    } else {
        // if I echo the $page->id here it shows me the correct mother page id
        return $page->id;
    }
}

private function loadSubPages($api) {
    $page = Page::where('api', $api)->first();
    $mother = $this->findMother($page->id);
    die('mother: ' . $mother); // $mother is empty
}

Anybody have an idea what I am missing here?

Alvin Bakker
  • 1,456
  • 21
  • 40
  • You are calling findMother recursively and you die on first call. Try to replace die with var_dump and you will see the result. I don't if is a good thing to call findMother recursively (many db queries). – Mirceac21 Dec 23 '15 at 16:19

2 Answers2

1

You should return the result of the function call :

do

return $this->findMother($page->parent_id);

instead of

$this->findMother($page->parent_id);

This way you will return the result

jiboulex
  • 2,963
  • 2
  • 18
  • 28
  • Ooh jeez. It must be my last working day for this year :$ You are right, I should've put something like `$mother = $this->findMother($page->parent_id);` and then return `$mother` – Alvin Bakker Dec 23 '15 at 16:33
0

Thanks to jiboulex I solved it with below changes:

private function findMother($id) {
    $page = Page::find($id);
    $return = $page->id;
    if($page->parent_id != 0 || $page->parent_id != null) {
        return $this->findMother($page->parent_id);
    } else {
        return $return;
    }
}
Alvin Bakker
  • 1,456
  • 21
  • 40