Laravel 8: How to return questions that have answers by withCount()

I'm working with Laravel 8 to develop my forum, and I want to return the questions that have answers.

So I added withCount() to my method which goes here:

public function index()
    {
        $questions = Question::latest()->limit(5)->get();
        $topAnswered = Question::withCount('answers')->get();
        dd($topAnswered);
    }

So $topAnswered should contain the questions that have already answered but it returns also some questions that have not answered yet!

So I need to fix that but don't know how to do that...

Note that I have this relation at the Question Model:

public function answers()
    {
        return $this->hasMany(Answer::class);
    }

And this one also at the Answer Model:

public function question()
    {
        return $this->belongsTo(Question::class);
    }

So if you know, how to return only the questions that have already answered, please let me know, I would really appreciate that.

Thanks in advance.

Answers 1

  • I think you'll be needing the having function be used as another selector in there

    $topAnswered = Question::withCount('answers')->having('answers_count', '>', 0)->get();
    

Related Articles