Pagination Laravel Api
Pagination laravel api, dalam laravel terdapat dua function untuk melakukan pagination yang di suipport oleh eloquent secara default, yaitu paginate() dan simplePaginate(), berikut merupakan contoh penggunaan paginate() dan simplePaginate()
paginate()
controller
Route::get('/testing', function () {
$data = User::paginate(5);
return response()->json($data);
});
response
{
"current_page": 1,
"data": [
{
"id": 1,
"username": "myusername",
"first_name": "John",
"last_name": "Wick",
"sex": "male",
"email": "tester@codingduluaja.online",
"created_at": "2024-02-16T14:05:28.000000Z",
"updated_at": "2024-02-16T14:05:28.000000Z"
}
],
"first_page_url": "http://localhost:8000/api/testing?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "http://localhost:8000/api/testing?page=1",
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
{
"url": "http://localhost:8000/api/testing?page=1",
"label": "1",
"active": true
},
{
"url": null,
"label": "Next »",
"active": false
}
],
"next_page_url": null,
"path": "http://localhost:8000/api/testing",
"per_page": 5,
"prev_page_url": null,
"to": 1,
"total": 1
}
simplePaginate()
controller
Route::get('/testing', function () {
$data = User::simplePaginate(5);
return response()->json($data);
});
response
{
"current_page": 1,
"data": [
{
"id": 1,
"username": "myusername",
"first_name": "John",
"last_name": "Wick",
"sex": "male",
"email": "tester@codingduluaja.online",
"created_at": "2024-02-16T14:05:28.000000Z",
"updated_at": "2024-02-16T14:05:28.000000Z"
}
],
"first_page_url": "http://localhost:8000/api/testing?page=1",
"from": 1,
"next_page_url": null,
"path": "http://localhost:8000/api/testing",
"per_page": 5,
"prev_page_url": null,
"to": 1
}