Pagination for data from a database

via

Db::select("...");

I fetch data from a database.
It is a lot of data. Therefore I would like to display them in a table with several pages. Each page should display 25 records. I wanted to solve this with a pagination, however, this does not work as thought.

<?php foreach($elements->paginate(10) as $element): ?>

This is how I get the first ten elements. How do I get the next ones?

You need a $pagination object and then a navigation that allows you to navigate between the pagination pages, should work similar to how it works with page collections, see

While it returns a Collection iterator by default, $db->query() fetches data as a Kirby\Toolkit\Obj which is not a Collection.
Maybe something like $db->lastResult()->paginate(10) ?

I have already tried this, but it does not work.
I get the following error: Call to undefined method Kirby\Toolkit\Pagination::pageURL()
My code:

controllers/data.php

<?php

return function () {

    $elements= Db::select('elements');

    return [
        'elements' => $elements
    ];
};

templates/data.php

<?php foreach($list = $elements->paginate(10) as $element): ?>
    <p><?= $element->id() ?></p>
    <p><?= $element->id() ?></p>
    <br>
<?php endforeach ?>


<?php $pagination = $list->pagination() ?>
<nav>
    <ul>

        <?php if ($pagination->hasPrevPage()): ?>
        <li>
            <a href="<?= $pagination->prevPageURL() ?>">‹</a>
        </li>
        <?php else: ?>
        <li>
            <span>‹</span>
        </li>
        <?php endif ?>

        <?php foreach ($pagination->range(10) as $r): ?>
        <li>
            <a<?= $pagination->page() === $r ? ' aria-current="page"' : '' ?> href="<?= $pagination->pageURL($r) ?>">
                <?= $r ?>
                </a>
        </li>
        <?php endforeach ?>

        <?php if ($pagination->hasNextPage()): ?>
        <li>
            <a href="<?= $pagination->nextPageURL() ?>">›</a>
        </li>
        <?php else: ?>
        <li>
            <span>›</span>
        </li>
        <?php endif ?>

    </ul>
</nav>

Yes, the problem is that the pagination object of a toolkit collection doesn’t have a page url… Same as problem described here: Pagination in Kirby 3 problem, Call to undefined method and here: Applying pagination to results from a database - #7 by Milos2504

And since the underlying problem doesn’t seem to be fixed yet…, I guess this needs some workaround.

What does this workaround look like?

I’ve created Db pagination for the virtual users, maybe this is helpful.

I’m planning to refactor the code above to make a copy of the kirby/Pagination.php at main · getkirby/kirby · GitHub and adapted it to make it work without using collections.

One workaround for your use case could be to convert your database entries into virtual children.