Search code examples
laravellumenlaravel-query-builderpaginatorlaravel-pagination

Laravel: Results of paginate() are inconstant across pages


I am having issue with the paginated results as follows :

Request :

GET http://localhost:1000/api/v1/public/blog/articles

Response :

{
    "current_page": 1,
    "data": [
        {
            "article_id": 43
        },
        {
            "article_id": 107
        },
        {
            "article_id": 171
        },
        {
            "article_id": 22
        },
        {
            "article_id": 86
        },
        {
            "article_id": 150
        },
        {
            "article_id": 1
        },
        {
            "article_id": 65
        },
        {
            "article_id": 129
        },
        {
            "article_id": 44
        }
    ],
    "first_page_url": "http://localhost:1000/api/v1/public/blog/articles?page=1",
    "from": 1,
    "last_page": 18,
    "last_page_url": "http://localhost:1000/api/v1/public/blog/articles?page=18",
    "next_page_url": "http://localhost:1000/api/v1/public/blog/articles?page=2",
    "path": "http://localhost:1000/api/v1/public/blog/articles",
    "per_page": "10",
    "prev_page_url": null,
    "to": 10,
    "total": 179
}

So, now If I request again in the same link, it shows a different set of articles with different ids. Also If I go to page=1 or page=2, each and every pages the results are inconstant.

I am not sure from where this issue is occuring, I want to mention that my other paginated queries are working fine except when I am trying to concat queries for getting a specific result as follows :

$query = DB::query();

// Then Concatenating other queries based on options

// Now Execute The Whole Query
$fetched_articles = $query->paginate(5);

It would be helpful, if anyone can describe the paginator flows here with the solution or workarounds.

Thanks in Advance !


Solution

  • According to Laravel documentation

    Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.

    so, you can not use groupBy in your query, if you want pagination.

    By the way, you can try this blog post, may be it will work for you.