2
2

More than 3 years have passed since last update.

Laravelで自作Paginatorを作る

Posted at

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を実装できます。

2
2
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
2
2