Support the ongoing development of Laravel.io →
Eloquent Routing Laravel
Last updated by @ajax30 1 week ago.
0
moderator Solution

Hello @ajax30

The mistake is in:

$tag = Tag::firstWhere('id', $tag_id);
$articles = Article::where('id', $tag->id)->orderBy('id', 'desc')->paginate($this->per_page);

You load the article with the same id as the tag and not the articles for the tag :)

What I should do is:

$tag = Tag::firstWhere('id', $tag_id);
$articles = Article::query()
    ->whereHas('tags', function (Builder $query) use ($tag): void {
        $query->where('id', $tag->id);
    })
    ->orderBy('id', 'desc')
    ->paginate($this->per_page);

ps, I see on your tag model public function article() but it can be multiple articles, for that I should call that function articles :)

0
Solution selected by @ajax30

Sign in to participate in this thread!

Eventy

Your banner here too?

Razvan ajax30 Joined 2 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.