Livewire 4 Pagination: Named Paginators, Cursors, URL State and the Queries Underneath

A complete Livewire 4 pagination guide: WithPagination, URL state, resetPage on filters, named paginators, cursorPaginate, N+1 fixes and Pest query-count tests.

Steven Richardson
Steven Richardson
· 18 min read

The orders dashboard was fine at 2,000 rows. At 180,000 it took four seconds to render page one, every filter change dumped the user onto an empty page 7, and the second table on the same screen jumped pages whenever the first one did. None of that is a Livewire bug. It is what happens when paginate(25) is treated as the whole of pagination rather than the first line of it.

This guide takes one component — an orders list that grows into a real dashboard — and works through every pagination decision that matters in production: where the page number lives, when to reset it, how to run two paginators side by side, which of the three paginate methods to use and what SQL each one emits, how to stop the N+1 that pagination makes worse, and how to prove the lot with Pest.

Add WithPagination to the orders component#

Pagination in Livewire starts with a trait, not a method call. As Livewire's pagination documentation puts it, every component containing pagination must use it. Livewire\WithPagination is what pulls the page number out of the component's state instead of the request, re-renders the component on a page change, and makes ->links() emit wire:click handlers rather than full-page anchors. Without the trait the paginator still renders, but the links navigate the browser away from your component and the Livewire state is lost.

Generate the component. Livewire 4 creates a single-file component by default, with the PHP class and the Blade template in one file under resources/views:

php artisan make:livewire pages::orders.index

That writes resources/views/pages/orders/⚡index.blade.php. If the lightning bolt or the single-file shape is not for you, both are config switches — the single-file versus multi-file trade-offs in Livewire 4 are worth reading before you commit a team to one. Here is the starting component:

<?php // resources/views/pages/orders/⚡index.blade.php

use Livewire\Attributes\Computed;
use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Order;

new class extends Component {
    use WithPagination;

    #[Computed]
    public function orders()
    {
        return Order::query()
            ->latest('placed_at')
            ->paginate(25);
    }
};
<div>
    <table>
        @foreach ($this->orders as $order)
            <tr wire:key="order-{{ $order->id }}">
                <td>{{ $order->reference }}</td>
                <td>{{ $order->total_in_pence / 100 }}</td>
            </tr>
        @endforeach
    </table>

    {{ $this->orders->links() }}
</div>

Two details carry weight later. The query lives behind a #[Computed] property, so it runs once per request no matter how many times the template touches $this->orders. And every row carries a wire:key — without it, Livewire's DOM diffing will reuse the wrong row after a page change, which looks exactly like a pagination bug and is not one.

Keep the page number in the URL, and know when to drop it#

By default Livewire writes the current page into the browser's query string as ?page=3. This is almost always what you want on a dashboard: a user can send the URL to a colleague, refresh without losing their place, and bookmark page 7 of an audit log. You get it for free from WithPagination — there is nothing to switch on.

There are two situations where it is actively wrong. A paginated list inside a modal should not rewrite the page URL, and neither should a list inside a dropdown or a tab the user has not navigated to. For those, add the companion trait:

use Livewire\WithoutUrlPagination;
use Livewire\WithPagination;

new class extends Component {
    use WithPagination, WithoutUrlPagination;
    // ...
};

With WithoutUrlPagination, paging still works but the page number lives in component state only, which also means it is not persisted across a full page load. That is the trade: the modal stops polluting the URL, and the modal also forgets where it was if the user refreshes.

While you are in the query string, decide what else belongs there. Filters usually do, and #[Url] is the clean way to put them there — the full treatment of #[Url] and query-string filters covers the as, history and keep arguments, and Livewire's own URL query parameters documentation is the reference for the attribute's signature. The rule of thumb: if two people should be able to see the same screen from the same link, the state belongs in the URL.

Reset the page when a filter changes#

This is the single most common pagination bug in Livewire applications, and it has a one-line fix that almost everybody writes six months too late. A user is on page 5. They type into the search box. The filtered result set now has two pages. Livewire still asks for page 5, the query returns zero rows, and the user sees an empty table alongside pagination links insisting there are results.

Livewire provides $this->resetPage() for exactly this. The reliable place to call it is an updated hook for each filter property, because those hooks fire when the property changes but not on mount — so a page number restored from the URL on first load survives:

use Livewire\Attributes\Url;
use Livewire\Attributes\Computed;
use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Order;

new class extends Component {
    use WithPagination;

    #[Url(as: 'q', history: true)]
    public string $search = '';

    #[Url]
    public string $status = '';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    #[Computed]
    public function orders()
    {
        return Order::query()
            ->when($this->search, fn ($q) => $q->where('reference', 'like', "%{$this->search}%"))
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->latest('placed_at')
            ->paginate(25);
    }
};

If you have more than two or three filters, the per-property hooks get repetitive. A single updated() hook with a property-name argument collapses them, with an allow-list so unrelated properties do not reset the page:

public function updated(string $property): void
{
    if (in_array($property, ['search', 'status', 'channel', 'perPage'], true)) {
        $this->resetPage();
    }
}

Note perPage in that list. Changing rows-per-page from 25 to 100 while on page 6 produces the same empty-table symptom, and the same fix applies. One caveat worth knowing before the next section: resetPage() with no arguments only resets the default paginator. If you have named your paginator, this call silently does nothing.

Bind the search input with a debounce so you are not firing a query per keystroke — wire:model.live.debounce.400ms is the usual starting point, and there is more nuance than that in building a debounced live search input.

Name the paginator when two lists share a page#

The moment a screen holds two paginated lists, they fight over ?page=. Click to page 3 of the orders table and the refunds table below it also jumps to page 3 — or, worse, to an empty page 3 it does not have. Both Laravel and Livewire key the page number off a query-string parameter, so the fix is to give each paginator its own parameter name.

Pass pageName to paginate():

#[Computed]
public function orders()
{
    return Order::query()->latest('placed_at')->paginate(25, pageName: 'orders-page');
}

#[Computed]
public function refunds()
{
    return Refund::query()->latest('issued_at')->paginate(10, pageName: 'refunds-page');
}

The URL now carries both independently: ?orders-page=3&refunds-page=1. This is where most implementations stop, and where the second bug starts. Every page-navigation method takes the same pageName argument, and all four are no-ops against a named paginator if you leave it off:

$this->resetPage(pageName: 'orders-page');
$this->setPage(2, pageName: 'orders-page');
$this->nextPage(pageName: 'orders-page');
$this->previousPage(pageName: 'orders-page');

So the filter hook from the previous step has to be updated too, or filtering the orders table leaves it stranded on orders-page=5:

public function updatedSearch(): void
{
    $this->resetPage(pageName: 'orders-page');
}

The lifecycle hooks follow the same rule. updatingPage() and updatedPage() only fire for the default paginator; a paginator named orders-page needs updatingOrdersPage(), studly-cased from the page name. If you would rather not encode the name in the method, the generic hooks receive it as a second argument:

public function updatedPaginators($page, $pageName): void
{
    logger()->debug('paginator moved', ['name' => $pageName, 'page' => $page]);
}

Two paginators in one component is the simplest arrangement, but two separate Livewire components on the same page have the same collision and the same fix. If you are building this on top of Flux, the same pageName discipline applies — the server-driven Flux table guide shows it wired into flux:pagination.

Pick between paginate, simplePaginate and cursorPaginate#

The three methods look interchangeable and are not. They emit different SQL, cost different amounts, and give the user different controls — Laravel's pagination documentation sets out the offset-versus-cursor trade-off in detail. Here is what each actually runs for page 3 of a 25-per-page orders list, taken from the query log.

paginate(25) runs two queries — a count to work out how many pages exist, then the page itself:

select count(*) as aggregate from `orders`;
select * from `orders` order by `placed_at` desc limit 25 offset 50;

simplePaginate(25) drops the count and fetches one extra row to decide whether a "next" link is needed:

select * from `orders` order by `placed_at` desc limit 26 offset 50;

cursorPaginate(25) drops the count and the offset, replacing the scan with a where clause against the last row of the previous page:

select * from `orders`
where (`placed_at` < '2026-11-18 09:14:02'
   or (`placed_at` = '2026-11-18 09:14:02' and `id` < 48213))
order by `placed_at` desc, `id` desc limit 26;

The practical decision: use paginate() while you need numbered pages and a total, and while the table is small enough that count(*) is cheap. On MySQL with InnoDB an unfiltered count(*) over a few hundred thousand rows is a full index scan — measurable but survivable. Add a where clause on an unindexed column and it stops being survivable.

Use simplePaginate() when the UI only offers next and previous. You lose total() and lastPage(), which means no "showing 51–75 of 184,302" and no jump-to-last-page. On a log viewer nobody misses either.

Use cursorPaginate() on genuinely large or write-heavy tables. Beyond the count saving, it fixes a correctness problem: with offset pagination, rows inserted while a user is reading push everything down, so page 2 repeats rows they already saw on page 1. Cursors anchor to a row, so inserts above them are invisible. The cost is that you lose page numbers entirely, and the ordering becomes load-bearing — which is the next step. For an endless-feed UI rather than a dashboard, cursors pair naturally with infinite scroll using wire:intersect.

Stabilise the ordering before switching to cursor pagination#

Cursor pagination encodes the ordered column values of the last row into the ?cursor= string and turns them into a where clause. That only produces a correct result if the ordering is total — every row must sort to a unique position. Order by a column with ties and the cursor cannot tell which of the tied rows it stopped at, so rows get skipped or repeated. This is the cause behind nearly every "cursor pagination is duplicating my records" report: a created_at column where a seeder or a bulk import wrote identical timestamps to thousands of rows.

The fix is a tiebreaker on a unique column, almost always the primary key:

#[Computed]
public function orders()
{
    return Order::query()
        ->when($this->status, fn ($q) => $q->where('status', $this->status))
        ->orderByDesc('placed_at')
        ->orderByDesc('id')      // tiebreaker: makes the ordering total
        ->cursorPaginate(25, cursorName: 'orders-cursor');
}

Laravel's latest() helper orders by one timestamp column alone, so ->latest()->cursorPaginate() is unsafe on any table where timestamps can collide. Write the two orderByDesc calls out explicitly.

Three further constraints come straight from Laravel's cursor pagination limitations and will misbehave rather than warn you:

  • Ordered columns must belong to the table being paginated. You cannot order a cursor-paginated orders query by customers.name through a join.
  • Ordered columns cannot be nullable. A nullable shipped_at will not produce a usable cursor; order by a coalesced expression aliased into the select, or pick a different column.
  • Query expressions in the order by are supported only when aliased and added to the select, and expressions with bindings are not supported at all.

Then add the index the where clause needs, or you have swapped a count scan for a filesort:

Schema::table('orders', function (Blueprint $table) {
    $table->index(['status', 'placed_at', 'id'], 'orders_status_placed_at_id_index');
});

The column order matters: equality filter first, then the sort columns in the order they appear in the order by. Confirm with EXPLAIN that the query uses the index and reports no Using filesort.

Kill the N+1 and the count query#

Pagination makes N+1 queries worse in a specific way: the symptom scales with perPage, so a page size of 25 hides what a page size of 100 makes obvious, and a dashboard that is fine in staging falls over the first time somebody picks "show 100". Each row in the orders table renders a customer name and a count of line items, which without eager loading costs two queries per row — 51 queries for 25 rows.

Eager load the relations and use a withCount aggregate rather than a per-row count():

#[Computed]
public function orders()
{
    return Order::query()
        ->with('customer:id,name')
        ->withCount('lines')
        ->when($this->status, fn ($q) => $q->where('status', $this->status))
        ->orderByDesc('placed_at')
        ->orderByDesc('id')
        ->paginate(25, pageName: 'orders-page');
}

The customer:id,name syntax restricts the eager-loaded select, which matters when the customers table has a wide row. withCount('lines') folds the count into a correlated subquery on the main query instead of running one per row.

The durable fix is to make the application refuse to lazy-load at all. Eloquent's strict mode turns every unguarded lazy load into an exception in development, so the N+1 fails the test suite rather than reaching production — see catching N+1 queries early with Eloquent strict mode for the Model::preventLazyLoading() setup and the environment guard around it.

That leaves the count query. On a filtered list it runs on every page change, every filter change, and every re-render that touches the computed property. If you must keep numbered pages on a large table, cache the total for the current filter combination rather than recomputing it — #[Computed(persist: true)] for caching heavy queries across requests is the Livewire-native way to do it, keyed carefully so that changing a filter changes the key. If you do not need numbered pages, delete the count by moving to simplePaginate() and stop paying for it.

Make pagination survive wire:navigate and the back button#

wire:navigate swaps pages over the wire and restores scroll position, which interacts with pagination in two places. First, Livewire's paginator scrolls to the top of the page after every page change by default — which, on a dashboard where the table sits below a filter bar, throws the user's eye to the masthead on every click. Point it at the table instead:

{{ $this->orders->links(data: ['scrollTo' => '#orders-table']) }}

Pass false instead of a selector to suppress the scroll entirely. Both forms are passed through to the pagination view, so a custom view has to honour them — more on that in the next step.

Second, the back button. Because the page number is written without pushing a history entry, paging through five pages and hitting back takes the user to the previous route, not to page 4. That is deliberate — otherwise a user who clicked through ten pages would need ten back presses to leave the screen. If a particular screen genuinely needs page-by-page history, drive the page from a #[Url(history: true)] property rather than the paginator's own state and call setPage() from its updated hook.

The prefetching side of wire:navigate is worth tuning here too, since a hovered pagination link is a high-confidence prefetch target; the wire:navigate prefetch and SPA-feel guide covers when hover prefetching costs more than it saves.

Publish an accessible custom pagination view#

Livewire ships Tailwind and Bootstrap pagination views and uses its own in preference to Laravel's whenever the paginator is rendered inside a component. Publishing them gives you ownership of the markup, which you need because the defaults are generic and because accessibility is where hand-rolled pagination usually fails.

php artisan livewire:publish --pagination

That drops four files into resources/views/vendor/livewire: tailwind.blade.php, tailwind-simple.blade.php, bootstrap.blade.php and bootstrap-simple.blade.php. To use a view of your own instead, either pass its name to links() or declare it on the component:

public function paginationView(): string
{
    return 'pagination.orders';
}

public function paginationSimpleView(): string
{
    return 'pagination.orders-simple';
}

A minimal accessible version. The nav carries a label, the current page is marked with aria-current, the disabled ends render as non-interactive text rather than disabled buttons, and a live region announces the range after each change so a screen-reader user is not left guessing:

<div>
    @if ($paginator->hasPages())
        <nav role="navigation" aria-label="Orders pagination">
            @if ($paginator->onFirstPage())
                <span aria-hidden="true">Previous</span>
            @else
                <button type="button"
                        wire:click="previousPage(pageName: '{{ $paginator->getPageName() }}')"
                        class="data-loading:opacity-50" rel="prev">Previous</button>
            @endif

            @foreach ($elements as $element)
                @if (is_array($element))
                    @foreach ($element as $page => $url)
                        <button type="button"
                                wire:click="setPage({{ $page }}, pageName: '{{ $paginator->getPageName() }}')"
                                @if ($page === $paginator->currentPage()) aria-current="page" @endif>
                            {{ $page }}
                        </button>
                    @endforeach
                @endif
            @endforeach

            @if ($paginator->hasMorePages())
                <button type="button"
                        wire:click="nextPage(pageName: '{{ $paginator->getPageName() }}')"
                        class="data-loading:opacity-50" rel="next">Next</button>
            @else
                <span aria-hidden="true">Next</span>
            @endif
        </nav>

        <p aria-live="polite" class="sr-only">
            Showing {{ $paginator->firstItem() }} to {{ $paginator->lastItem() }}
            of {{ $paginator->total() }} orders
        </p>
    @endif
</div>

Note $paginator->getPageName() rather than a hard-coded string — that is what makes one view work for both the orders and refunds paginators. And data-loading:opacity-50 pairs Livewire 4's automatic loading attribute with a Tailwind variant, giving visual feedback without disabling the button and stealing focus mid-interaction.

Test the pagination with Pest, including a query-count assertion#

Pagination bugs are cheap to test and expensive to find in production, because every one of them is invisible on the fixture data most tests run against. Seed past the page boundary — if the page size is 25, seed 60 rows, not 30 — and assert on what the user sees rather than on the paginator object.

composer require pestphp/pest-plugin-livewire --dev
use App\Models\Order;
use Livewire\Livewire;

it('shows the second page of orders', function () {
    Order::factory()->count(60)->sequence(fn ($s) => [
        'placed_at' => now()->subMinutes($s->index),
    ])->create();

    Livewire::test('pages::orders.index')
        ->call('setPage', 2, pageName: 'orders-page')
        ->assertViewHas('orders', fn ($orders) => $orders->count() === 25
            && $orders->currentPage() === 2);
});

it('resets to page one when the search changes', function () {
    Order::factory()->count(60)->create();

    Livewire::test('pages::orders.index')
        ->call('setPage', 3, pageName: 'orders-page')
        ->set('search', 'ORD-9')
        ->assertViewHas('orders', fn ($orders) => $orders->currentPage() === 1);
});

it('keeps the two paginators independent', function () {
    Order::factory()->count(60)->create();
    Refund::factory()->count(40)->create();

    Livewire::test('pages::orders.index')
        ->call('setPage', 2, pageName: 'orders-page')
        ->assertViewHas('refunds', fn ($refunds) => $refunds->currentPage() === 1);
});

The one that catches regressions nobody else catches is a query-count assertion. It fails the moment somebody removes an eager load or adds a per-row lookup to the Blade template:

use Illuminate\Support\Facades\DB;

it('renders a page of orders in a fixed number of queries', function () {
    Order::factory()->count(60)->hasLines(3)->for(Customer::factory())->create();

    $queries = 0;
    DB::listen(function () use (&$queries) { $queries++; });

    Livewire::test('pages::orders.index')->assertOk();

    // 1 count + 1 orders page + 1 eager-loaded customers = 3
    expect($queries)->toBe(3);
});

Pin the number to what you measured, not to what you hope. When it changes, the diff tells you whether the change was deliberate. The broader patterns — testing URL state, asserting on #[Url] properties, and the assertSet and assertSee vocabulary — are covered in testing Livewire 4 components with Pest.

Ship the dashboard#

What started as paginate(25) is now a list that keeps its place in the URL, resets cleanly when filters change, runs two independent paginators without them colliding, uses a cursor with a total ordering and a matching composite index on the large table, renders in a known and asserted number of queries, and announces itself properly to a screen reader. None of it is exotic. All of it is the difference between a table that works at 2,000 rows and one that works at 180,000.

Three places to go next. If this dashboard is built on Flux, wire the same pageName discipline into Flux's server-driven table rather than reinventing the markup. If the list is really a feed, swap the numbered pages for infinite scroll with wire:intersect and keep the cursor. And if the same table lives inside an admin panel, the Filament v5 guide to large-table query tuning applies the same count-query and index reasoning to a panel whose Blade you do not control.

FAQ#

Why is my Livewire pagination not working?

In almost every case the component is missing the Livewire\WithPagination trait. Without it the paginator renders links that navigate the browser rather than updating the component, so clicking page 2 either reloads the route or appears to do nothing. Add use WithPagination; to the component. If the trait is present and page 2 is empty, the cause is usually an unreset page number after a filter change rather than the pagination itself.

How do I use two paginators on one Livewire page?

Give each one a distinct pageName: paginate(25, pageName: 'orders-page') and paginate(10, pageName: 'refunds-page'). The two page numbers are then tracked separately in the query string. Crucially, pass the same pageName to resetPage(), setPage(), nextPage() and previousPage() as well, because those methods target the default paginator and will silently do nothing against a named one.

What does resetPage do in Livewire?

$this->resetPage() sets the paginator back to page 1 from anywhere in the component. You call it when the result set changes shape — a new search term, a changed filter, a different rows-per-page value — so that a user sitting on page 5 of the old results is not shown an empty page 5 of the new ones. The usual place is an updatedPropertyName() hook, which fires on change but not on mount, so a page number restored from the URL survives the initial load.

What is the difference between paginate, simplePaginate and cursorPaginate?

paginate() runs a count(*) plus a limit/offset query and gives you numbered pages and a total. simplePaginate() skips the count and fetches one extra row, giving you only next and previous links but one query instead of two. cursorPaginate() skips both the count and the offset, using a where clause against the previous page's last row — the fastest of the three on large tables, at the cost of page numbers and a requirement for strictly unique ordering.

Why does cursor pagination show duplicate or missing rows?

The ordering is not total — two or more rows sort to the same position, so the cursor cannot determine where the previous page ended. This shows up most often when ordering by created_at on data where a seeder or bulk import wrote identical timestamps. Add a unique tiebreaker to the order, normally the primary key: ->orderByDesc('placed_at')->orderByDesc('id'). Laravel's latest() helper orders by one column only, so avoid it for cursor-paginated queries.

How do I remove the page number from the URL in Livewire?

Add the Livewire\WithoutUrlPagination trait alongside WithPagination. Pagination continues to work, but the page number lives in component state only and never reaches the query string. The trade-off is that the current page is no longer persisted across a full page load or shareable by URL, so reserve it for lists inside modals, dropdowns and tabs where URL state would be noise.

How do I stop Livewire scrolling to the top when changing page?

Pass a scrollTo value through the links() method: {{ $orders->links(data: ['scrollTo' => false]) }} disables the scroll entirely, and passing a CSS selector such as '#orders-table' scrolls to the nearest matching element instead. On a dashboard where the table sits below a filter bar, pointing at the table keeps the user's place. A custom pagination view has to read and honour the value itself.

How do I customise the Livewire pagination view?

Run php artisan livewire:publish --pagination to copy the four default views into resources/views/vendor/livewire, then edit them directly. To use a view of your own somewhere else, either pass its name to links('pagination.orders') in the template or declare a paginationView() method — and paginationSimpleView() for simple paginators — on the component returning the view name. Use $paginator->getPageName() inside the view so the same markup serves named and unnamed paginators.

Does pagination work with wire:navigate?

Yes, and the page number is preserved in the URL across wire:navigate visits. The thing to be aware of is history: Livewire replaces the current history entry rather than pushing a new one, so the browser's back button leaves the screen rather than stepping back one page. If a screen genuinely needs page-by-page history, drive the page from a #[Url(history: true)] property and call setPage() from its updated hook instead of relying on the paginator's own URL handling.

Steven Richardson
Steven Richardson

CTO at Digitonic. Writing about Laravel, architecture, and the craft of leading software teams from the west coast of Scotland.