ImWaller's avatar

Turn pagination into json

Hello everyone, I try to create a custom infinity loading pagination with splade and vue. I try to use Model::paginate and return the eloquent but I want to return as json. Any help?

0 likes
4 replies
Sinnbeck's avatar

If vue sends an Accept: application/json header, laravel will automatically return it as json. Just return the paginated model as response

PovilasKorop's avatar

By default, Laravel transforms the response into JSON if you just return a Model or Eloquent Collection.

Example with Pagination

public function index()
{
	return User::paginate();
}

Will return:

{
    "current_page": 1,
    "data": [
        {
            "id": 1,
            "name": "Prof. Marcos Ratke",
            "email": "[email protected]",
            "email_verified_at": "2023-01-04T12:26:19.000000Z",
            "created_at": "2023-01-04T12:26:20.000000Z",
            "updated_at": "2023-01-04T12:26:20.000000Z"
        },
        {
            "id": 2,
            "name": "Sincere Casper",
            "email": "[email protected]",
            "email_verified_at": "2023-01-04T12:26:19.000000Z",
            "created_at": "2023-01-04T12:26:20.000000Z",
            "updated_at": "2023-01-04T12:26:20.000000Z"
        },

        // ... other users
    ],
    "first_page_url": "http://laravel.test/api/users?page=1",
    "from": 1,
    "last_page": 2,
    "last_page_url": "http://laravel.test/api/users?page=2",
    "links": [
        {
            "url": null,
            "label": "« Previous",
            "active": false
        },
        {
            "url": "http://laravel.test/api/users?page=1",
            "label": "1",
            "active": true
        },
        {
            "url": "http://laravel.test/api/users?page=2",
            "label": "2",
            "active": false
        },
        {
            "url": "http://laravel.test/api/users?page=2",
            "label": "Next »",
            "active": false
        }
    ],
    "next_page_url": "http://laravel.test/api/users?page=2",
    "path": "http://laravel.test/api/users",
    "per_page": 15,
    "prev_page_url": null,
    "to": 15,
    "total": 20
}

As you can see, the users are wrapped in data, and the main JSON contains more data about pages.

I've just written a quick tutorial for it, for future reference.

1 like
ImWaller's avatar
ImWaller
OP
Best Answer
Level 1

Thanks for the replies but the solution was to bind the prop and use the @js(...) directive...

Sinnbeck's avatar

@ImWaller Uhh ok dont see how that makes it possible to get the newest data using ajax? But ok

Please or to participate in this conversation.