LaravelでPaginationを実装するときは、Laravelフレームワークで提供されている LengthAwarePaginatorを継承して、独自のPaginatorクラスを実装すると便利です。
ブログの記事を想定してサンプルコードを示します。
PostPaginator.php
<?php
use Illuminate\Pagination\LengthAwarePaginator;
class PostPaginator extends LengthAwarePaginator {
private $postList;
public function __construct(PostList $list, PostCount $allCount, Limit $limit, PostStatus $postStatus)
{
parent::__construct($list, $allCount, limit, null, []);
if(!is_null($postStatus) {
$this->appends('status', postStatus);
}
}
}
このページネーターはLaravelのLengthAwarePaginatorを継承しているので、簡単に表示することができます。表示の仕方はLaravelのPaginationリンクの表示形式を変更するを御覧ください。
今回はブログ記事の公開、非公開というステータスを表現することを想定してpostStatusというのを追加しています。appendsの部分を追加することによって、ページネータの発行するURLのクエリパラメーターにpageだけではなく、独自のパラメーターを追加することができます。
これで手軽に独自のPaginatorを実装できます。