Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

armingdev's avatar

Nested relations using subqueries

Hi everyone,

I need little help with nested relations, il give an example of code.

I have 3 tables: forums, forum_categories, topics

Forum has many ForumCategories

ForumCategories has many Topics

Now, I need to query to get All forums with his ForumCategores and take last topic from each ForumCategory. I have used Jonathan Reinin example of the Dynamic relationships in Laravel using subqueries described HERE

ForumCategory Model methods described in Jonathan post:


    public function lastTopic()
    {
        return $this->belongsTo(Topic::class, 'last_topic_id');
    }

    public function scopeWithLastTopic($query)
    {
        return $query->addSelect(['last_topic_id' => Topic::select('id')
            ->whereColumn('forum_category_id', 'forum_categories.id')
            ->latest()
            ->take(1)
        ])->with('lastTopic');
    }

but it looks like it dosent work with multiple levels ...

So when following this example, when I do in ForumController:


    public function listForumCategories() {
        return Forum::with('forumCategories.scopeWithLastTopic')->get();
    }

Error that I get :

ArgumentCountError
Too few arguments to function App\Models\ForumCategory::scopeWithLastTopic(), 0 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 669 and exactly 1 expected

Any ideas how to make this working? Thx

0 likes
4 replies
webrobert's avatar

Idk 🤷‍♂️ Tried removing scope from the with?


    public function listForumCategories() {
        return Forum::with('forumCategories.withLastTopic')->get();
    }

armingdev's avatar

Nahh, I think issue is because im eager loading first relation forumCategories and that cause issues with loading next relation ... Im not sure .. i stuck at this ..

Please or to participate in this conversation.