Laravel relation returning empty
<p>I want to get all the books under a certain category. The category has many subjects and books are linked to subjects.</p>

<p>My code:</p>

<pre><code>class BookCategory extends Model {

    public function subjects() {
        return $this-&gt;hasMany('BookSubject', 'category_id', 'id');
    }

    public function getBooksAttribute() {
        return Books::whereHas('subjects', function ($query) {
            return $query-&gt;join('book_category', 'book_category.id', '=', 'book_subject.subject_id')
                         -&gt;where('book_category.id', $this-&gt;id);
        })-&gt;get();
    }
}
</code></pre>

<p>and my Books model:</p>

<pre><code>class Books extends Model {

    public function subjects() {
        return $this-&gt;belongsToMany('BookSubject', 'book_by_subject', 'book_id', 'subject_id');
    }
}
</code></pre>

<p>If I do:</p>

<pre><code>$cats = \App\Models\BookCategory::all();
foreach ($cats as $c) {
    echo $c-&gt;books-&gt;count();
}
</code></pre>

<p>It's always returning 0 for all the rows. What I'm I doing wrong?</p>