1

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!

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.