LoginSignup
1
0

More than 1 year has passed since last update.

【Laravel】ページネーション件数を指定しないと、デフォルトで15件になる

Posted at

はじめに

Laravelではpaginateメソッドを使って簡単にページネーションを実装することが出来る。

実装の中で、ページネーション機能を作るわけではないがページネーションの形式(LengthAwarePaginator)でデータを取得する為、件数を指定せずにpaginateメソッドを使用したことがあった。

paginate メソッドの引数に件数を渡さなければ、全件?たくさん?取得してくれるのかなと思いきや、15件しか取得せずおどろいたので、調べたことをまとめておく。

paginateメソッドはどこにあるのか

paginate メソッドは Illuminate/Database/Eloquent/Builder.phpに定義されていた。

public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
		$page = $page ?: Paginator::resolveCurrentPage($pageName);

    $total = $this->toBase()->getCountForPagination();

    $perPage = ($perPage instanceof Closure
        ? $perPage($total)
        : $perPage
    ) ?: $this->model->getPerPage();

    $results = $total
        ? $this->forPage($page, $perPage)->get($columns)
        : $this->model->newCollection();

    return $this->paginator($results, $total, $perPage, $page, [
        'path' => Paginator::resolveCurrentPath(),
        'pageName' => $pageName,
    ]);
}

$perPageの引数を渡さなかった場合、 $this->model->getPerPage(); が呼ばれている。

$this→modelIlluminate/Database/Eloquent/Builder.php で下記の通り定義されている。

/**
 * The model being queried.
 *
 * @var \Illuminate\Database\Eloquent\Model
 */
protected $model;

// 中略

/**
 * Set a model instance for the model being queried.
 *
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @return $this
 */
public function setModel(Model $model)
{
    $this->model = $model;

    $this->query->from($model->getTable());

    return $this;
}

Modelで定義されているデフォルトのperPage

下記はvendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php からの抜粋。

クラス変数 $perPage = 15; がページ上部で定義されており、セッター、ゲッターの実装で $perPage を返している。

/**
 * The number of models to return for pagination.
 *
 * @var int
 */
protected $perPage = 15;

/**
 * Get the number of models to return per page.
 *
 * @return int
 */
public function getPerPage()
{
    return $this->perPage;
}

/**
 * Set the number of models to return per page.
 *
 * @param  int  $perPage
 * @return $this
 */
public function setPerPage($perPage)
{
    $this->perPage = $perPage;

    return $this;
}

さいごに

やはりフレームワークの機能を使う時は、きちんと意図した挙動をしているか確認する必要があるなと改めて思った。

またフレームワーク内部のソースコードで、こういう風にセッターゲッターの実装がされているのだなと勉強になった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0