Pagination with tags

I’m doing a blog with this controller:

<?php

// This is a controller file that contains the logic for the blog template.

return function($site, $pages, $page) {

    $perpage  = $page->perpage()->int();
    $articles = $page->children()->visible()->flip()->paginate(($perpage >= 1) ? $perpage : 5);

    if($tag = param('tag')) {
        $tag = urldecode(param('tag'));
        $articles = $articles->filterBy('tags', $tag, ',');
    }

    return [
        'articles'   => $articles,
        'pagination' => $articles->pagination(),
        'tag'        => $tag,
    ];

};

And when I filter by tag (ex: /tag:design) the filter works but not the pagination. It shows the articles with the tag and also pages with the message: “This blog does not contain any articles yet.”

What am I doing wrong?

You’re paginating the articles first, then filtering them.

You should filter the articles first.

You’re right!

Thank you