Skip to content

Commit 405779f

Browse files
committed
Added support for overriding per_page as a query parameter to an API
1 parent 41b1ca6 commit 405779f

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"laravel/framework": "^8.0|^9.0",
1717
"laravel/passport": "^10.1.0",
1818
"spatie/laravel-permission": "^3.2",
19-
"spatie/laravel-query-builder": "^2.3",
19+
"spatie/laravel-query-builder": "^2.3|^3.0||^4.0|^5.0",
2020
"phpdocumentor/reflection-docblock": "^4.3|^5.0",
2121
"lcobucci/jwt": "^4.0",
2222
"league/oauth2-server": "^8.3.2"

src/Http/Controllers/ApiController.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,18 @@ protected function getBuilder()
7272
return $this->getModelClass()::query();
7373
}
7474

75+
/**
76+
* Get the effective perPage value, either overriden from the request or fallback on the set property
77+
*
78+
* @return int
79+
*/
80+
protected function getPerPage()
81+
{
82+
$requestPerPage = (int) $this->getRequest()->query('per_page', $this->perPage);
83+
$requestPerPage = $requestPerPage <= $this->perPage ? $requestPerPage : $this->perPage;
84+
return $this->perPage > 0 ? $requestPerPage : $this->perPage;
85+
}
86+
7587
/**
7688
* Display a listing of the resource.
7789
*
@@ -85,7 +97,7 @@ protected function defaultIndex()
8597
$data = [];
8698
if(($builder = $this->getBuilder()) instanceof Builder) {
8799
$data = $this->perPage > 0
88-
? $builder->paginate($this->perPage)
100+
? $builder->paginate($this->getPerPage())
89101
: $builder->get();
90102

91103
if($data instanceof AbstractPaginator) {

0 commit comments

Comments
 (0)