Posts Learn Components new Snippets new Categories Tags About
/

How to Get Next Cursor for Cursor Paginate In Laravel

Learn how to get the next cursor value for cursor pagination in Laravel

Created on Sep 19, 2021

37 views

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

new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻