概要
LaravelでAPIを作成しており、ページネーションの処理を実装しようとしてました。
DBから取ってくるデータを使うので、Eloquentのpaginateを使いました。
そこで、試しに0のパラメータを渡したところ、15件が返ってきたので、その調査をしました。
TL;DR
- Modelで
perPageを設定していないと、デフォルトの15が適用される
調査
PhpStorm を駆使して、該当のプログラムに辿り着きました。
Illuminate/Database/Eloquent/Builder.php https://github.com/laravel/framework/blob/a81f23d0ccd2fefa7fa9b79649ab23811631d9bf/src/Illuminate/Database/Eloquent/Builder.php#L708
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
perPage が 0の場合は、 $this->model->getPerPage(); が呼ばれます。model の perPage は設定していないと、 $perPage = 15; が適応され、15となっていました。
備考
$perPage を0で定義すると、 Illuminate/Pagination/LengthAwarePaginator.php で ErrorException : Division by zero と怒られました。