Idk 🤷♂️ Tried removing scope from the with?
public function listForumCategories() {
return Forum::with('forumCategories.withLastTopic')->get();
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
@armingdev now laravel has built-in Has One Of Many relationships, incuding latestOfMany https://laravel.com/docs/8.x/eloquent-relationships#has-one-of-many
public function latestTopic()
{
return $this->hasOne(Order::class)->latestOfMany();
}
public function listForumCategories() {
return Forum::with('forumCategories.latestTopic')->get();
}
Please or to participate in this conversation.