Home / Snippets / How to Get Next Cursor for Cursor Paginate In Laravel
How to Get Next Cursor for Cursor Paginate In Laravel cover

How to Get Next Cursor for Cursor Paginate In Laravel

2.2K

3 years ago

0 comments

In Laravel 8 there's new cursor pagination method that's more efficient and consumes minimal resources.
While paginate and simplePaginate create queries using the SQL "offset" clause, cursor pagination works by constructing "where" clauses that compare the values of the ordered columns contained in the query, providing the most efficient database performance available amongst all of Laravel's pagination methods. This method of pagination is particularly well-suited for large data-sets and "infinite" scrolling user interfaces.
To get the next cursor you can call the "nextCursor" method and then get the "encode" value that will return as a string. This is important if you want to place the cursor as a class property.
<?php

$postTemp = Post::cursorPaginate(12, ['*'], 'cursor', Cursor::fromEncoded($nextCursor));
$nextCursor = $postTemp->nextCursor()->encode();

Full Code Example


The full code example will be as follows.
<?php

$posts = new Collection();
$nextCursor = null;
hasMorePages = false;

$postTemp = Post::cursorPaginate(12, ['*'], 'cursor', Cursor::fromEncoded($nextCursor));

$posts->push(...$postTemp->items());

if ($hasMorePages = $postTemp->hasMorePages()) {
    $nextCursor = $postTemp->nextCursor()->encode();
}

Good Usecase

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this