Readouble

Laravel master ペジネーション

イントロダクションIntroduction

他のフレームワークのペジネーションは苦痛に満ちています。LaravelのペジネータはクエリビルダEloquent ORMに統合されており、データベースの結果を簡単、お手軽にペジネーションできます。In other frameworks, pagination can be very painful. Laravel's paginator is integrated with the query builder[/docs/{{version}}/queries] and Eloquent ORM[/docs/{{version}}/eloquent] and provides convenient, easy-to-use pagination of database results out of the box. The HTML generated by the paginator is compatible with the Bootstrap CSS framework[http://getbootstrap.com/].

基本的な使用法Basic Usage

クエリビルダの結果Paginating Query Builder Results

アイテムをペジネーションするには多くの方法があります。一番簡単な方法は、クエリビルダEloquent querypaginateメソッドを使う方法です。paginateメソッドは、ユーザが表示している現在のページに基づき、正しいアイテム数とオフセットを指定する面倒を見ます。デフォルトではHTTPリクエストのpageクエリ文字列引数の値により現在ページが決められます。もちろんこの値はLaravelが自動的に探し、さらにペジネーターが挿入するリンクを自動的に生成します。There are several ways to paginate items. The simplest is by using the paginate method on the query builder[/docs/{{version}}/queries] or an Eloquent query[/docs/{{version}}/eloquent]. The paginate method automatically takes care of setting the proper limit and offset based on the current page being viewed by the user. By default, the current page is detected by the value of the page query string argument on the HTTP request. Of course, this value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator.

以下の例では、paginateに一つだけ引数を渡しており、「ページごと」に表示したいアイテム数です。この例ではページごとに15アイテムを表示するように指定しています。In this example, the only argument passed to the paginate method is the number of items you would like displayed "per page". In this case, let's specify that we would like to display 15 items per page:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * アプリケーションの全ユーザー表示
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::table('users')->paginate(15);

        return view('user.index', ['users' => $users]);
    }
}

Note: note 現在groupBy文を使用したペジネーション操作は、Laravelで正しく実行できません。groupByを使用したペジネーションを使用する必要がある場合はデータベースクエリを実行し、その結果を元にペジネーターを自前で作成してください。{note} Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually.

シンプル・ペジネーション"Simple Pagination"

「次」と「前」のリンクだけのシンプルなペジネーションビューを表示したい場合はsimplePaginateメソッドを使用し、より効率的にクエリすべきでしょう。これはビューに正確なページ番号を表示する必要がない、巨大なデータセットを扱う場合に便利です。If you only need to display simple "Next" and "Previous" links in your pagination view, you may use the simplePaginate method to perform a more efficient query. This is very useful for large datasets when you do not need to display a link for each page number when rendering your view:

$users = DB::table('users')->simplePaginate(15);

Eloquentの結果Paginating Eloquent Results

さらにEloquentモデルもペジネーションできます。例としてUserモデルの15アイテムをページ付け表示してみましょう。ご覧の通り、クエリビルダ結果のペジネーションを行う記法はきれいでわかりやすいものです。You may also paginate Eloquent[/docs/{{version}}/eloquent] queries. In this example, we will paginate the User model with 15 items per page. As you can see, the syntax is nearly identical to paginating query builder results:

$users = App\User::paginate(15);

もちろんwhere節のような制約をクエリに指定した後にpaginateを呼び出すこともできます。Of course, you may call paginate after setting other constraints on the query, such as where clauses:

$users = User::where('votes', '>', 100)->paginate(15);

Elqouentモデルをページづけするときにも、simplePaginateメソッドを使用できます。You may also use the simplePaginate method when paginating Eloquent models:

$users = User::where('votes', '>', 100)->simplePaginate(15);

独自ペジネータ作成Manually Creating A Paginator

渡された配列を元にして、ペジネーションインスンタンスを作成したいこともあります。必要に応じてIlluminate\Pagination\Paginatorか、Illuminate\Pagination\LengthAwarePaginatorインスタンスを生成することで実現できます。Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator instance, depending on your needs.

Paginatorクラスは結果にセットされているアイテムの総数を知る必要はありません。そのためクラスは最終ページのインデックスを取得するメソッドを持っていません。LengthAwarePaginatorPaginatorとほとんど同じ引数を取りますが、結果にセットされているアイテム総数も指定する必要がある点が異なっています。The Paginator class does not need to know the total number of items in the result set; however, because of this, the class does not have methods for retrieving the index of the last page. The LengthAwarePaginator accepts almost the same arguments as the Paginator; however, it does require a count of the total number of items in the result set.

言い換えれば、PaginatorはクエリビルダとEloquentに対するsimplePaginateメソッドに対応し、一方のLengthAwarePaginatorpaginateに対応しています。In other words, the Paginator corresponds to the simplePaginate method on the query builder and Eloquent, while the LengthAwarePaginator corresponds to the paginate method.

Note: note 自前でペジネーターインスタンスを生成する場合、ペジネーターに渡す結果の配列を自分で"slice"する必要があります。その方法を思いつかなければ、array_slice PHP関数を調べてください。{note} When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator. If you're unsure how to do this, check out the array_slice[http://php.net/manual/en/function.array-slice.php] PHP function.

ペジネーション結果の表示Displaying Pagination Results

paginateメソッドを呼び出す場合、Illuminate\Pagination\LengthAwarePaginatorインスタンスを受け取ります。simplePaginateメソッドを呼び出すときは、Illuminate\Pagination\Paginatorインスタンスを受け取ります。これらのオブジェクトは結果を表すたくさんのメソッドを提供しています。こうしたヘルパメソッドに加え、ペジネーターインスタンスはイテレータでもあり、配列としてループ処理できます。つまり結果を取得したら、その結果とページリンクをBladeを使い表示できます。When calling the paginate method, you will receive an instance of Illuminate\Pagination\LengthAwarePaginator. When calling the simplePaginate method, you will receive an instance of Illuminate\Pagination\Paginator. These objects provide several methods that describe the result set. In addition to these helpers methods, the paginator instances are iterators and may be looped as an array. So, once you have retrieved the results, you may display the results and render the page links using Blade[/docs/{{version}}/blade]:

<div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $users->links() }}

linksメソッドは結果の残りのページヘのリンクをレンダーします。それらの各リンクにはpageクエリー文字列変数が含まれています。linksメソッドが生成するHTMLはBootstrap CSSフレームワークと互換性があることを覚えておいてください。The links method will render the links to the rest of the pages in the result set. Each of these links will already contain the proper page query string variable. Remember, the HTML generated by the links method is compatible with the Bootstrap CSS framework[https://getbootstrap.com].

ペジネーターURIのカスタマイズCustomizing The Paginator URI

setPathメソッドにより、ペジネーターがリンクを生成するときに使用するURIをカスタマイズできます。たとえばペジネーターでhttp://example.com/custom/url?page=Nのようなリンクを生成したい場合、setPathメソッドにcustom/urlを渡してください。The setPath method allows you to customize the URI used by the paginator when generating links. For example, if you want the paginator to generate links like http://example.com/custom/url?page=N, you should pass custom/url to the setPath method:

Route::get('users', function () {
    $users = App\User::paginate(15);

    $users->setPath('custom/url');

    //
});

ペジネーションリンクの追加Appending To Pagination Links

ペジネーションリンクにクエリ文字列を付け加えたいときは、appendsメソッドを使います。たとえばsort=votesを各ペジネーションリンクに追加する場合には、以下のようにappendsを呼び出します。You may append to the query string of pagination links using the appends method. For example, to append sort=votes to each pagination link, you should make the following call to appends:

{{ $users->appends(['sort' => 'votes'])->links() }}

ペジネーションのURLに「ハッシュフラグメント」を追加したい場合は、fragmentメソッドが使用できます。例えば各ペジネーションリンクの最後に#fooを追加したい場合は、以下のようにfragmentメソッドを呼び出します。If you wish to append a "hash fragment" to the paginator's URLs, you may use the fragment method. For example, to append #foo to the end of each pagination link, make the following call to the fragment method:

{{ $users->fragment('foo')->links() }}

結果のJSON変換Converting Results To JSON

Laravelのペジネーター結果クラスはIlluminate\Contracts\Support\Jsonableインターフェイス契約を実装しており、toJsonメソッドを提示しています。ですからペジネーション結果をJSONにとても簡単に変換できます。またルートやコントローラーアクションからシンプルにペジネーターインスタンスを返せば、JSONへ変換されます。The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable Interface contract and expose the toJson method, so it's very easy to convert your pagination results to JSON. You may also convert a paginator instance to JSON by simply returning it from a route or controller action:

Route::get('users', function () {
    return App\User::paginate();
});

ペジネーターのJSON形式はtotalcurrent_pagelast_pageなどのメタ情報を含んでいます。実際の結果オブジェクトはJSON配列のdataキーにより利用できます。ルートから返されたペジネーターインスタンスにより生成されるJSONの一例を見てください。The JSON from the paginator will include meta information such as total, current_page, last_page, and more. The actual result objects will be available via the data key in the JSON array. Here is an example of the JSON created by returning a paginator instance from a route:

{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "from": 1,
   "to": 15,
   "data":[
        {
            // Result Object
        },
        {
            // Result Object
        }
   ]
}

ペジネーションビューのカスタマイズCustomizing The Pagination View

デフォルトで、ペジネーションリンクを表示するためのビューはBootstrap CSSフレームワークを用いてレンダーされます。しかし、Bootstrapを使っていない場合でも、そうしたリンクをレンダーする独自のビューを自由に定義できます。ペジネータインスタンスのlinksメソッドを呼び出す際に、ビュー名をメソッドの最初の引数として渡してください。By default, the views rendered to display the pagination links are compatible with the Bootstrap CSS framework. However, if you are not using Bootstrap, you are free to define your own views to render these links. When calling the links method on a paginator instance, pass the view name as the first argument to the method:

{{ $paginator->links('view.name') }}

しかし、vendor:publishコマンドを使用し、resources/views/vendorディレクトリへペジネーションビューを作成し、カスタマイズする方法が一番簡単でしょう。However, the easiest way to customize the pagination views is by exporting them to your resources/views/vendor directory using the vendor:publish command:

php artisan vendor:publish --tag=laravel-pagination

このコマンドは、resources/views/vendor/paginationディレクトリへビューを設置します。このディレクトリのdefault.blade.phpファイルが、デフォルトペジネーションビューに対応します。ペジネーションのHTMLを変更するには、ただこのファイルを編集するだけです。This command will place the views in the resources/views/vendor/pagination directory. The default.blade.php file within this directory corresponds to the default pagination view. Simply edit this file to modify the pagination HTML.

ペジネータインスタンスメソッドPaginator Instance Methods

ペジネータインスタンスは以下の追加ペジネーション情報を提供しています。Each paginator instance provides additional pagination information via the following methods:

  • $results->count()$results->count()
  • $results->currentPage()$results->currentPage()
  • $results->firstItem()$results->firstItem()
  • $results->hasMorePages()$results->hasMorePages()
  • $results->lastItem()$results->lastItem()
  • $results->lastPage() (simplePaginateでは使用不可)$results->lastPage() (Not available when using simplePaginate)
  • $results->nextPageUrl()$results->nextPageUrl()
  • $results->perPage()$results->perPage()
  • $results->previousPageUrl()$results->previousPageUrl()
  • $results->total() (simplePaginateでは使用不可)$results->total() (Not available when using simplePaginate)
  • $results->url($page)$results->url($page)

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作