Taylor Swift Taylor Swift - 5 months ago 12
PHP Question

Laravel recursion - calling itself in a class

My current code:

public function countThreads() {
$count = $this->threads->count();
if ($this->hasSubforum()) {
foreach ($this->subforums as $subforum) {
$count += $this->countThreads($subforum);
}
}
return $count;
}


I am currently accessing the "thread" as
$this
inside my model. I need to pass in the
$subforum
to itself but how can I do that in a class?

In my controller, I'm simply doing:

$forum = Forum::where('id', $id)->first();
$forum->countThreads();


How can I do recursion with this? thanks!

Answer

You don't need to pass any arguments*, you can call the countThreads method on the subforum $subforum->countThreads()

public function countThreads() 
{
    $count = $this->threads->count();
    if ($this->hasSubforum()) {
        foreach ($this->subforums as $subforum) {
            $count += $subforum->countThreads();
        }
    }

    return $count;
}

If you really want to pass it in as an argument, the correct way would be to write it as a service outside of the model