Code Day's Night

ichikawayのブログ

自前のページング処理でもLaravelのページング用htmlを出力する方法

Laravel5.1を使ってます。

LaravelのEloquentやクエリビルダーを使わない場合でも、View側で下図のようにLaravelのページングのhtmlを出力したい場合の話。

f:id:ichikaway:20161007161051p:plain

 Illuminate\Pagination\LengthAwarePaginatorクラスを使います。

$paginator = new LengthAwarePaginator($items, $total, $limit, $page);
$paginator->setPath($request->url());

というように第1引数に配列やコレクションオブジェクトをセットし、第2引数に総レコード数、第3引数に1ページに表示する件数、第4引数に現在表示しているページ数をセットするだけ。
ページング用のURLはsetPath()でセットします。

<?php echo $paginator->render(); ?>

あとはView側でrender()メソッドを呼ぶとhtmlが出力されます。
ですので、DB以外から取得した配列データなどでも簡単にページングのhtmlが作成できます。

LengthAwarePaginatorクラスのコンストラクタはこのようになってます。

/**
* Create a new paginator instance.
*
* @param mixed $items
* @param int $total
* @param int $perPage
* @param int|null $currentPage
* @param array $options (path, query, fragment, pageName)
* @return void
*/
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{

参考

Pagination - Laravel - The PHP Framework For Web Artisans

https://readouble.com/laravel/5.1/ja/pagination.html