PHPackages                             juampi92/cursor-pagination - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. juampi92/cursor-pagination

AbandonedArchivedLibrary[API Development](/categories/api)

juampi92/cursor-pagination
==========================

Cursor pagination made easy for Laravel

v1.6.0(5y ago)70193.4k↓50%15[1 issues](https://github.com/juampi92/cursor-pagination/issues)[1 PRs](https://github.com/juampi92/cursor-pagination/pulls)MITPHPPHP &gt;=7.1.0

Since Feb 24Pushed 3y agoCompare

[ Source](https://github.com/juampi92/cursor-pagination)[ Packagist](https://packagist.org/packages/juampi92/cursor-pagination)[ Docs](https://github.com/juampi92/cursor-pagination)[ RSS](/packages/juampi92-cursor-pagination/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (5)Versions (12)Used By (0)

Cursor Pagination for Laravel
=============================

[](#cursor-pagination-for-laravel)

[![Latest Version](https://camo.githubusercontent.com/35baeacbfe513eb393d73c4fb40e787a78ba851059b9fc48b53b0ea368ffd9a1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6a75616d706939322f637572736f722d706167696e6174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/juampi92/cursor-pagination/releases)[![Build Status](https://camo.githubusercontent.com/5ed0570288bd338c0f00ef4b2ba9e266ddc18bfe4957560de320b84b38001f57/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6a75616d706939322f637572736f722d706167696e6174696f6e2f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/juampi92/cursor-pagination)[![StyleCI](https://camo.githubusercontent.com/3711cb0d45fbecf0d462918d70bf50520cd7807c7814c14afd3d870dbc52e284/68747470733a2f2f7374796c6563692e696f2f7265706f732f3132323538333039372f736869656c643f6272616e63683d6d6173746572)](https://styleci.io/repos/122583097)[![Total Downloads](https://camo.githubusercontent.com/89bf66047169553854535448b3f384c8b9aa11707c2cd55770ec82c1449c4ae0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a75616d706939322f637572736f722d706167696e6174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/juampi92/cursor-pagination)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

**⚠️ Cursor pagination is archived.** This is because [cursor pagination](https://laravel.com/docs/pagination#cursor-pagination) is built into Laravel out of the box so is no longer needed. We recommend that you use the native package, or if you must, fork this one.

---

This package provides a cursor based pagination already integrated with Laravel's [query builder](https://laravel.com/docs/master/queries) and [Eloquent ORM](https://laravel.com/docs/master/eloquent). It calculates the SQL query limits automatically by checking the requests GET parameters, and automatically builds the next and previous urls for you.

Installation
------------

[](#installation)

You can install this package via composer using:

```
composer require juampi92/cursor-pagination
```

The package will automatically register itself.

### Config

[](#config)

To publish the config file to `config/cursor_pagination.php` run:

```
php artisan vendor:publish --provider="Juampi92\CursorPagination\CursorPaginationServiceProvider" --tag="config"
```

This will publish the following [file](config/cursor_pagination.php). You can customize the name of the GET parameters, as well as the default items per page.

How does it work
----------------

[](#how-does-it-work)

The main idea behind a cursor pagination is that it needs a context to know what results to show next. So instead of saying `page=2`, you say `next_cursor=10`. The result is the same as the old fashioned page pagination, but now you have more control on the output, cause `next_cursor=10` should always return the same (unless some records are deleted).

This kind of pagination is useful when you sort using the latest first, so you can keep an infinite scroll using `next_cursor` whenever you get to the bottom, or do a `previous_cursor` whenever you need to refresh the list at the top, and if you send the first cursor, the results will only fetch the new ones.

#### Pros

[](#pros)

- New rows don't affect the result, so no duplicated results when paginating.
- Filtering by an indexed cursor is way faster that using database offset.
- Using previous cursor to avoid duplicating the first elements.

#### Cons

[](#cons)

- No previous page, although the browser still has them.
- No navigating to arbitrary pages (you must know the previous result to know the next ones).

Basically, **it's perfect for infinite scrolling!**

Basic Usage
-----------

[](#basic-usage)

### Paginating Query Builder Results

[](#paginating-query-builder-results)

There are several ways to paginate items. The simplest is by using the `cursorPaginate` method on the **query builder** or an **Eloquent query**. The `cursorPaginate` method automatically takes care of setting the proper limit and fetching the next or previous elements based on the cursor being viewed by the user. By default, the `cursor` is detected by the value of the page query string argument on the HTTP request. This value is automatically detected by the package taking your custom config into account, and is also automatically inserted into links and meta generated by the paginator.

```
public function index()
{
    $users = DB::table('users')->cursorPaginate();
    return $users;
}
```

### Paginating Eloquent Results

[](#paginating-eloquent-results)

You may also paginate **Eloquent queries**. In this example, we will paginate the `User` model with `15` items per page. As you can see, the syntax is identical to paginating query builder results:

```
$users = User::cursorPaginate(15);
```

Of course, you may call paginate after setting other constraints on the query, such as where clauses:

```
$users = User::where('votes', '>', 100)->cursorPaginate(15);
```

Or sorting your results:

```
$users = User::orderBy('id', 'desc')->cursorPaginate(15);
```

Don't worry, the package will detect if the model's primary key is being used for sorting, and it will adapt itself so the next and previous work as expected.

### Identifier

[](#identifier)

The paginator identifier is basically the cursor attribute. The model's attribute that will be used for paginating. It's really important that this identifier is **unique** on the results. Duplicated identifiers could cause that some records are not showed, so be careful.

*If the query is not sorted by the identifier, the cursor pagination might not work as expected.*

#### Auto-detecting Identifier

[](#auto-detecting-identifier)

If no identifier is defined, the cursor will try to figure it out by itself. First, it will check if there's any orderBy clause. If there is, it will take the **first column** that is sorted and will use that. If there is not any orderBy clause, it will check if it's an Eloquent model, and will use it's `primaryKey` (by default it's 'id'). And if it's not an Eloquent Model, it'll use `id`.

##### Example

[](#example)

```
// Will use Booking's primaryKey
Bookings::cursorPaginate(10);
```

```
// Will use hardcoded 'id'
DB::table('bookings')->cursorPaginate(10);
```

```
// Will use 'created_by'
Bookings::orderBy('created_by', 'asc')
    ->cursorPaginate(10);
```

#### Customizing Identifier

[](#customizing-identifier)

Just define the `identifier` option

```
// Will use _id, ignoring everything else.
Bookings::cursorPaginate(10, ['*'], [
    'identifier'      => '_id'
]);
```

### Date cursors

[](#date-cursors)

By default, the identifier is the model's primaryKey (or `id` in case it's not an Eloquent model) so there are no duplicates, but you can adjust this by passing a custom `identifier` option. In case that specified identifier is casted to date or datetime on Eloquent's `$casts` property, the paginator will convert it into **unix timestamp** for you.

You can also specify it manually by adding a `[ 'date_identifier' => true ]` option.

##### Example

[](#example-1)

Using Eloquent (make sure Booking Model has `protected $casts = ['datetime' => 'datetime'];`)

```
// It will autodetect 'datetime' as identifier,
//   and will detect it's casted to datetime.
Bookings::orderBy('datetime', 'asc')
    ->cursorPaginate(10);
```

Using Query

```
// It will autodetect 'datetime' as identifier,
//   but since there is no model, you'll have to
//   specify the 'date_identifier' option to `true`
DB::table('bookings')
    ->orderBy('datetime', 'asc')
    ->cursorPaginate(10, ['*'], [
        'date_identifier' => true
    ]);
```

### Inherits Laravel's Pagination

[](#inherits-laravels-pagination)

You should know that CursorPaginator inherits from Laravel's AbstractPaginator, so methods like `withPath`, `appends`, `fragment` are available, so you can use those to build the url, but you should know that the default url creation of this package includes query params that you might already have.

Displaying Pagination Results
-----------------------------

[](#displaying-pagination-results)

### Converting to JSON

[](#converting-to-json)

A basic return will transform the paginator to JSON and will have a result like this:

```
Route::get('api/v1', function () {
    return App\User::cursorPaginate();
});
```

Calling `api/v1` will output:

```
{
   "path": "api/v1?",
   "previous_cursor": "10",
   "next_cursor": "3",
   "per_page": 3,
   "next_page_url": "api/v1?next_cursor=3",
   "prev_page_url": "api/v1?previous_cursor=1",
   "data": [
        {}
   ]
}
```

### Using a Resource Collection

[](#using-a-resource-collection)

By default, Laravel's API Resources when using them as collections, they will output a paginator's metadata into `links` and `meta`.

```
{
   "data":[
        {}
   ],
   "links": {
       "first": null,
       "last": null,
       "prev": "api/v1?previous_cursor=1",
       "next": "api/v1?next_cursor=3"
   },
   "meta": {
       "path": "api/v1?",
       "previous_cursor": "1",
       "next_cursor": "3",
       "per_page": 3
   }
}
```

Understanding the previous cursor
---------------------------------

[](#understanding-the-previous-cursor)

It's important to clarify that the previous cursor does NOT work like the next one. The next cursor makes the paginator return the elements that follow that cursor.

So in the case of the next cursor being `10`, that pagination should return `next + 1`, `next + 2`, `next + 3`. So that works as expected.

The previous cursor though it's not `prev - 1`, `prev - 2`, `prev - 3`. No. It does not return the adjacent elements, or the 'context' for that cursor. What it does instead is pretty interesting:

Let's assume we do a simple fetch and it returns elements `[10, 9, 8]`. If we do a `prev=10`, it will return empty, cause those are the first elements. So if we now add 5 more to that: from the 15 to the 11, and we do `prev=10` again, the result will be `[15, 14, 13]`. **NOT** `[13, 12 ,11]`.

That's because previous works like a filter. It shows the first 'per\_page' items that are before that cursor. The order is the same as in the next cursor, so it fetches the latest ones.

The same logic can be used when combining cursors: `next=13&prev=10` will output the missing two elements: `[12, 11]`, so you can complete the list without fetching any extra items.

Customizing per page results
----------------------------

[](#customizing-per-page-results)

With this plugin you can specify the perPage number by many ways.

You can set the `cursor_pagination.per_page` config, so if you don't send any parameters, it will use that as the default.

You can also use an array. The purpose of the array declaration is to separate whenever it's a previous cursor, or a next / default cursor. This way, when you do a *'refresh'*, you can fetch more results than if you are simply scrolling.

To configure that, set `$perPage = [15, 5]`. That way it'll fetch 15 when you do a `previous_cursor`, and 5 when you do a normal fetch or a `next_cursor`.

Customizing param names
-----------------------

[](#customizing-param-names)

On the config, change `identifier_name` to change the word `cursor`. Examples: `cursor`, `id`, `pointer`, etc.

Change `navigation_names` to change the words `['previous', 'next']`. Examples: `['before', 'after']` , `['min', 'max']`

##### Transforming the result:

[](#transforming-the-result)

Edit `transform_name` to format the string differently:

- For `previousCursor` use 'camel\_case'
- For `previous-cursor` use 'kebab\_case'.
- For `previous_cursor` use 'snake\_case'.

Using `null` defaults to camelCase.

API Docs
--------

[](#api-docs)

### Paginator custom options

[](#paginator-custom-options)

```
new CursorPaginator(array|collection $items, array|int $perPage, array options = [
    // Attribute used for choosing the cursor. Used primaryKey on Eloquent Models as default.
    'identifier'       => 'id',
    'identifier_alias' => 'id',
    'date_identifier'  => false,
    'path'             => request()->path(),
]);
```

(*The items must have a $item-&gt;{$identifier} property.*)

Eloquent Builder and Query Builder's macro:

```
cursorPaginate(array|int $perPage, array $cols = ['*'], array options = []): CursorPaginator;
```

### Paginator methods

[](#paginator-methods)

```
$resutls->hasMorePages(): bool;
$results->nextCursor(): string|null;
$results->prevCursor(): string|null;
$results->previousPageUrl(): string|null;
$results->nextPageUrl(): string|null;
$results->url(['next' => 1]): string;
$results->count(): int;
```

Note: all cursors are casted as strings.

### Identifier Alias

[](#identifier-alias)

Sometimes we need to use the paginator on a JOIN query. This might have duplicated columns, so we have to specify one for the sorting. Since Mysql doesn't allow us to use a selector alias on a WHERE condition, we have to use the `table`.`column` name instead.

```
$following = $user->following()
    ->orderBy('follows.created_at', 'desc')
    ->cursorPaginate(10, ['*'], [
        'date_identifier' => true,
        'identifier' => 'follows.created_at',
        'identifier_alias' => 'created_at',
    ]);
```

By default, the package will guess that the `identifier_alias` is the column name you specify, so if you order by `follows.created_at`, it will try to use the models `created_at` as identifier (by using the alias).

Testing
-------

[](#testing)

Run the tests with:

```
vendor/bin/phpunit
```

Credits
-------

[](#credits)

- [Juan Pablo Barreto](https://github.com/juampi92)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

40

—

FairBetter than 87% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community12

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 82.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~111 days

Recently: every ~180 days

Total

10

Last Release

1992d ago

PHP version history (2 changes)v1.0.0PHP &gt;=7.0.0

v1.4.0PHP &gt;=7.1.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/1f8d31c9bb6d7862e21aac7af0f7b2615dc06485b4c30b19b8d9fdffaa42c712?d=identicon)[juampi92](/maintainers/juampi92)

---

Top Contributors

[![juampi92](https://avatars.githubusercontent.com/u/2080215?v=4)](https://github.com/juampi92 "juampi92 (29 commits)")[![patrickomeara](https://avatars.githubusercontent.com/u/571773?v=4)](https://github.com/patrickomeara "patrickomeara (6 commits)")

---

Tags

apilaravellaravel5paginationphpapilaravelpagination

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/juampi92-cursor-pagination/health.svg)

```
[![Health](https://phpackages.com/badges/juampi92-cursor-pagination/health.svg)](https://phpackages.com/packages/juampi92-cursor-pagination)
```

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[resend/resend-laravel

Resend for Laravel

1191.4M6](/packages/resend-resend-laravel)[api-platform/laravel

API Platform support for Laravel

59126.4k5](/packages/api-platform-laravel)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
