Skip to content

Database: Pagination ​

Introduction ​

Model queries can be paginated with a single call. Like Laravel's paginate(), DotBlaze reads the current page from the page query string parameter, counts the total number of rows, and fetches only the rows for that page.

Basic Usage ​

Paginating Model Queries ​

Call Paginate on a model or at the end of any model query. The argument is the number of items per page (15 by default):

csharp
public async Task<IActionResult> Index() =>
    View(await Post.Scope(Post.Latest).With(p => p.User).Paginate(10));

Paginate runs two queries: a COUNT for the total and a Skip/Take query for the page. Give the query an order (here the Latest scope sorts by id) so pages are stable.

A page number below 1 is treated as 1. A page past the end returns an empty Items collection.

Choosing the Page Manually ​

Outside an HTTP request there is no query string, so the page defaults to 1. Pass page explicitly when you need a specific page:

csharp
var page = await Book.OrderByDesc(b => b.Price).Paginate(perPage: 2, page: 2);

page.Total;        // 5
page.LastPage;     // 3
page.HasMorePages; // true

Simple Pagination ​

When the page only needs "previous" and "next" links, SimplePaginate skips the COUNT query: it fetches one row more than the page size to know whether another page exists.

csharp
var posts = await Post.OrderByDesc(p => p.Id).SimplePaginate(15); // SimplePaginator<Post>

Cursor Pagination ​

CursorPaginate continues after the last value of the previous page (WHERE id > 120) instead of skipping rows, so it stays fast on large tables and does not repeat or skip rows when rows are added meanwhile. It suits infinite scrolling and "load more" buttons. Order by a unique column:

csharp
var posts = await Post.Query().CursorPaginate(p => p.Id, perPage: 15);                    // oldest first
var newest = await Post.Query().CursorPaginate(p => p.Id, perPage: 15, descending: true);

The cursor is read from the cursor query string parameter (or pass cursor:). NextPageUrl and PreviousPageUrl carry it; NextCursor and PreviousCursor are the raw values for an API. Unlike Paginate, there is no total and no page numbers. A damaged cursor shows the first page.

Paginating Query Builder Results ​

DB.Table queries have Paginate and SimplePaginate too; the items are rows (dictionaries):

csharp
var users = await DB.Table("users").OrderBy("name").Paginate(15);

Displaying Pagination Results ​

Paginate returns a Paginator<T>. Its Items property is a collection of the models on the current page:

html
@model Paginator<Post>

@foreach (var post in Model.Items)
{
    <article>
        <a href="@Route("posts.show", new { post = post.Id })">@post.Title</a>
        <p>by @post.User?.Name</p>
    </article>
}

@if (Model.Items.IsEmpty())
{
    <p>No posts yet.</p>
}

Links() renders Tailwind-styled links, like Laravel's $paginator->links(): previous, the page numbers around the current page (with ... for gaps), and next. SimplePaginator and CursorPaginator render previous and next only:

html
@Model.Links()

For your own markup, Url(page) returns the current path with page set and the rest of the query string kept (so filters such as ?search=dotblaze survive):

html
<div class="mt-6 flex justify-between text-sm">
    @if (!Model.OnFirstPage) { <a href="@Model.Url(Model.CurrentPage - 1)">&larr; Newer</a> } else { <span></span> }
    @if (Model.HasMorePages) { <a href="@Model.Url(Model.CurrentPage + 1)">Older &rarr;</a> }
</div>

Outside a request, Url(3) returns just ?page=3.

Converting Results to JSON ​

A Paginator<T> returned from a controller is serialized like any other object, and the models in Items follow the model serialization rules ([Hidden], [Appends], ...):

csharp
public async Task<IActionResult> Index() => Json(await Post.Paginate());
json
{
  "items": [ { "id": 1, "title": "Sample post 1", "excerpt": "..." } ],
  "total": 12,
  "perPage": 15,
  "currentPage": 1,
  "lastPage": 1,
  "hasMorePages": false,
  "onFirstPage": true
}

Paginator Reference ​

MemberDescription
ItemsCollection<T> of the models on this page.
TotalTotal number of matching rows.
PerPageItems per page.
CurrentPageThe current page number.
LastPageNumber of the last page (at least 1).
HasMorePagestrue if there is a page after this one.
OnFirstPagetrue on page 1.
Url(int page)URL for the given page, keeping the current query string.
PreviousPageUrl, NextPageUrlURLs of the neighbouring pages, or null.
FirstItem, LastItemNumbers of the first and last item on this page ("Showing 16 to 30 of 50").
Links(onEachSide = 2)Page links as HTML.

SimplePaginator<T> has Items, PerPage, CurrentPage, HasMorePages, OnFirstPage, Url, PreviousPageUrl, NextPageUrl, and Links(). CursorPaginator<T> has Items, PerPage, NextCursor, PreviousCursor, HasMorePages, OnFirstPage, PreviousPageUrl, NextPageUrl, and Links().

Complete Example: Paginated Blog ​

Start with the complete blog. Replace only PostController.Index with:

csharp
public async Task<IActionResult> Index() =>
    View(await Post.OrderByDesc(post => post.Id).Paginate(perPage: 2));

Replace resources/views/post/Index.blade.html with:

html
@model DotBlaze.Paginator<Blog.Models.Post>
@extends('layouts.app')
@section('title', "Posts")
@section('content')
    <h1>Posts</h1>
    <a href="{{ Route('posts.create') }}">Create a post</a>
    @forelse (var post in Model.Items)
        <p><a href="{{ Route('posts.show', new { post = post.Id }) }}">{{ post.Title }}</a></p>
    @empty
        <p>No posts on this page.</p>
    @endforelse
    <p>{{ Model.Total }} posts in total</p>
    {{ Model.Links() }}
@endsection

Create three posts through the form. /posts shows the newest two and a next-page link; /posts?page=2 shows the remaining post. /posts?page=999 has no items. This replaces the walkthrough's “latest 20” view, so update any test asserting its exact empty-state text. In Razor (.cshtml) render links as @Model.Links(); in Blade use the braces shown here.