Readouble

Laravel 5.7 データベース:ペジネーション

イントロダクションIntroduction

他のフレームワークのペジネーションは苦痛に満ちています。LaravelのペジネータはクエリビルダEloquent ORMに統合されており、データベースの結果を簡単、お手軽にペジネーションできます。ペジネータが生成するHTMLは、Bootstrap CSSフレームワークコンパチブルです。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[https://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. 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を呼び出すこともできます。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[https://secure.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

withPathメソッドにより、ペジネーターがリンクを生成するときに使用するURIをカスタマイズできます。たとえばペジネーターでhttp://example.com/custom/url?page=Nのようなリンクを生成したい場合、withPathメソッドにcustom/urlを渡してください。The withPath 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 withPath method:

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

    $users->withPath('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() }}

ペジネーションリンクウィンドウの調整Adjusting The Pagination Link Window

ペギネータのURL「ウィンドウ」の両サイドに、いくつの追加のリンクを表示するかを調整できます。デフォルトでは、メインのペジネータリンクの両サイドに3つのリンクが表示されます。この数を調整するには、onEachSideメソッドを使用します。You may control how many additional links are displayed on each side of the paginator's URL "window". By default, three links are displayed on each side of the primary paginator links. However, you may control this number using the onEachSide method:

{{ $users->onEachSide(5)->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 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,
   "first_page_url": "http://laravel.app?page=1",
   "last_page_url": "http://laravel.app?page=4",
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "path": "http://laravel.app",
   "from": 1,
   "to": 15,
   "data":[
        {
            // 結果のオブジェクト
        },
        {
            // 結果のオブジェクト
        }
   ]
}

ペジネーションビューのカスタマイズ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') }}

// ビューへデータを渡す
{{ $paginator->links('view.name', ['foo' => 'bar']) }}

しかし、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ディレクトリへビューを設置します。このディレクトリのbootstrap-4.blade.phpファイルが、デフォルトのペジネーションビューに当ります。ペジネーションHTMLを変更するために、このファイルを編集できます。This command will place the views in the resources/views/vendor/pagination directory. The bootstrap-4.blade.php file within this directory corresponds to the default pagination view. You may edit this file to modify the pagination HTML.

デフォルトのペジネーションビューとして、他のファイルを指定したい場合は、AppServiceProviderの中で、ペジネータのdefaultViewdefaultSimpleViewメソッドを使用します。If you would like to designate a different file as the default pagination view, you may use the paginator's defaultView and defaultSimpleView methods within your AppServiceProvider:

use Illuminate\Pagination\Paginator;

public function boot()
{
    Paginator::defaultView('view-name');

    Paginator::defaultSimpleView('view-name');
}

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

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

メソッドMethod 説明Description
$results->count()$results->count() 現在のページのアイテム数取得Get the number of items for the current page.
$results->currentPage()$results->currentPage() 現在のページ数Get the current page number.
$results->firstItem()$results->firstItem() 現在ページの最初のアイテムが何番目か取得Get the result number of the first item in the results.
$results->getOptions()$results->getOptions() ペジネータオプション取得Get the paginator options.
$results->getUrlRange($start, $end)$results->getUrlRange($start, $end) 一定範囲のペジネーションURLを取得Create a range of pagination URLs.
$results->hasMorePages()$results->hasMorePages() 複数ページへアイテムを分割できる数があるか判定Determine if there are enough items to split into multiple pages.
$results->lastItem()$results->lastItem() 現在ページの最後のアイテムが何番目か取得Get the result number of the last item in the results.
$results->lastPage()$results->lastPage() 利用可能な最終ページ数取得(simplePaginateでは使用できない)Get the page number of the last available page. (Not available when using simplePaginate).
$results->nextPageUrl()$results->nextPageUrl() 次ページのURL取得Get the URL for the next page.
$results->onFirstPage()$results->onFirstPage() ペジネータが最初のページを扱っているか判定Determine if the paginator is on the first page.
$results->perPage()$results->perPage() ページごとに表示するアイテム数The number of items to be shown per page.
$results->previousPageUrl()$results->previousPageUrl() 前ページのURL取得Get the URL for the previous page.
$results->total()$results->total() データ領域にある、条件に一致するアイテムの総数(simplePaginateでは使用できない)Determine the total number of matching items in the data store. (Not available when using simplePaginate).
$results->url($page)$results->url($page) 指定したページのURL取得Get the URL for a given page number.

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作