Readouble

Livewire v3 ペジネーション

ペジネーション

Laravelのページネーション機能を使用すると、データのサブセットをクエリし、ユーザーがそれらの結果のページ間を移動できるようにします。Laravel's pagination feature allows you to query a subset of data and provides your users with the ability to navigate between pages of those results.

Laravelのページネーターは静的なアプリケーション向けに設計されているため、非Livewireアプリでは、各ページナビゲーションは、目的のページ(?page=2)を含む新しいURLへの完全なブラウザアクセスをトリガーします。Because Laravel's paginator was designed for static applications, in a non-Livewire app, each page navigation triggers a full browser visit to a new URL containing the desired page (?page=2).

ただし、Livewireコンポーネント内でページネーションを使用すると、ユーザーは同じページにとどまりながらページ間を移動できます。 Livewireは、現在のページでURLクエリ文字列を更新するなど、舞台裏のすべてを処理します。However, when you use pagination inside a Livewire component, users can navigate between pages while remaining on the same page. Livewire will handle everything behind the scenes, including updating the URL query string with the current page.

基本的な使い方Basic usage

以下は、一度に10個の投稿のみを表示するShowPostsコンポーネント内でページネーションを使用する最も基本的な例です。Below is the most basic example of using pagination inside a ShowPosts component to only show ten posts at a time:

warning Warning! WithPaginationトレイトを使用する必要があります Livewireのページネーション機能を利用するには、ページネーションを含む各コンポーネントはLivewire\WithPaginationトレイトを使用する必要があります。[!warning] You must use the WithPagination trait To take advantage of Livewire's pagination features, each component containing pagination must use the Livewire\WithPagination trait.

<?php

namespace App\Livewire;

use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Post;

class ShowPosts extends Component
{
    use WithPagination;

    public function render()
    {
        return view('show-posts', [
            'posts' => Post::paginate(10),
        ]);
    }
}
<div>
    <div>
        @foreach ($posts as $post)
            <!-- ... -->
        @endforeach
    </div>

    {{ $posts->links() }}
</div>

ご覧のとおり、Post::paginate()メソッドを使用して表示される投稿の数を制限するだけでなく、$posts->links()を使用してページナビゲーションリンクをレンダリングします。As you can see, in addition to limiting the number of posts shown via the Post::paginate() method, we will also use $posts->links() to render page navigation links.

Laravelを使用したページネーションの詳細については、Laravelの包括的なページネーションドキュメントを確認してください。For more information on pagination using Laravel, check out Laravel's comprehensive pagination documentation[https://laravel.com/docs/pagination].

URLクエリ文字列のトラッキングを無効にするDisabling URL query string tracking

デフォルトでは、Livewireのページネーターは、ブラウザのURLのクエリ文字列で現在のページを追跡します(例:?page=2)。By default, Livewire's paginator tracks the current page in the browser URL's query string like so: ?page=2.

Livewireのページネーションユーティリティを引き続き使用したいが、クエリ文字列のトラッキングを無効にしたい場合は、WithoutUrlPaginationトレイトを使用できます。If you wish to still use Livewire's pagination utility, but disable query string tracking, you can do so using the WithoutUrlPagination trait:

use Livewire\WithoutUrlPagination;
use Livewire\WithPagination;
use Livewire\Component;

class ShowPosts extends Component
{
    use WithPagination, WithoutUrlPagination; // [tl! highlight]

    // ...
}

これで、ページネーションは期待どおりに機能しますが、現在のページはクエリ文字列に表示されません。 これは、現在のページがページ変更間で保持されないことも意味します。Now, pagination will work as expected, but the current page won't show up in the query string. This also means the current page won't be persisted across page changes.

スクロール動作のカスタマイズCustomizing scroll behavior

デフォルトでは、Livewireのページネーターは、ページ変更ごとにページの一番上にスクロールします。By default, Livewire's paginator scrolls to the top of the page after every page change.

links()メソッドのscrollToパラメーターにfalseを渡すことで、この動作を無効にできます。You can disable this behavior by passing false to the scrollTo parameter of the links() method like so:

{{ $posts->links(data: ['scrollTo' => false]) }}

または、CSSセレクターをscrollToパラメーターに指定することもできます。Livewireは、そのセレクターに一致する最も近い要素を見つけ、ナビゲーションのたびにその要素にスクロールします。Alternatively, you can provide any CSS selector to the scrollTo parameter, and Livewire will find the nearest element matching that selector and scroll to it after each navigation:

{{ $posts->links(data: ['scrollTo' => '#paginated-posts']) }}

ページのリセットResetting the page

結果をソートまたはフィルタリングするとき、ページ番号を1にリセットしたいことがよくあります。When sorting or filtering results, it is common to want to reset the page number back to 1.

このため、Livewireは$this->resetPage()メソッドを提供し、コンポーネント内のどこからでもページ番号をリセットできます。For this reason, Livewire provides the $this->resetPage() method, allowing you to reset the page number from anywhere in your component.

次のコンポーネントは、検索フォームが送信された後にこのメソッドを使用してページをリセットする方法を示しています。The following component demonstrates using this method to reset the page after the search form is submitted:

<?php

namespace App\Livewire;

use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Post;

class SearchPosts extends Component
{
    use WithPagination;

    public $query = '';

    public function search()
    {
        $this->resetPage();
    }

    public function render()
    {
        return view('show-posts', [
            'posts' => Post::where('title', 'like', '%'.$this->query.'%')->paginate(10),
        ]);
    }
}
<div>
    <form wire:submit="search">
        <input type="text" wire:model="query">

        <button type="submit">Search posts</button>
    </form>

    <div>
        @foreach ($posts as $post)
            <!-- ... -->
        @endforeach
    </div>

    {{ $posts->links() }}
</div>

これで、ユーザーが結果の5ページにいて、「Search posts」を押して結果をさらにフィルタリングした場合、ページは1にリセットされます。Now, if a user was on page 5 of the results and then filtered the results further by pressing "Search posts", the page would be reset back to 1.

利用可能なページナビゲーションメソッドAvailable page navigation methods

$this->resetPage()に加えて、Livewireはコンポーネントからプログラムでページ間を移動するためのその他の便利なメソッドを提供します。In addition to $this->resetPage(), Livewire provides other useful methods for navigating between pages programmatically from your component:

メソッドMethod 説明Description
$this->setPage($page)$this->setPage($page) ページネーターを特定のページ番号に設定しますSet the paginator to a specific page number
$this->resetPage()$this->resetPage() ページを1に戻しますReset the page back to 1
$this->nextPage()$this->nextPage() 次のページに進みますGo to the next page
$this->previousPage()$this->previousPage() 前のページに進みますGo to the previous page

複数のページネーターMultiple paginators

LaravelとLivewireの両方がURLクエリ文字列パラメーターを使用して現在のページ番号を保存および追跡するため、単一のページに複数のページネーターが含まれている場合は、それらに異なる名前を割り当てることが重要です。Because both Laravel and Livewire use URL query string parameters to store and track the current page number, if a single page contains multiple paginators, it's important to assign them different names.

問題をより明確に示すために、次のShowClientsコンポーネントを考えてみましょう。To demonstrate the problem more clearly, consider the following ShowClients component:

use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Client;

class ShowClients extends Component
{
    use WithPagination;

    public function render()
    {
        return view('show-clients', [
            'clients' => Client::paginate(10),
        ]);
    }
}

ご覧のとおり、上記のコンポーネントには、ページネーションされたクライアントのセットが含まれています。 ユーザーがこの結果セットの2ページに移動すると、URLは次のようになります。As you can see, the above component contains a paginated set of clients. If a user were to navigate to page 2 of this result set, the URL might look like the following:

http://application.test/?page=2

ページにページネーションも使用するShowInvoicesコンポーネントも含まれているとします。 各ページネーターの現在のページを個別に追跡するには、次のように2番目のページネーターの名前を指定する必要があります。Suppose the page also contains a ShowInvoices component that also uses pagination. To independently track each paginator's current page, you need to specify a name for the second paginator like so:

use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Invoices;

class ShowInvoices extends Component
{
    use WithPagination;

    public function render()
    {
        return view('show-invoices', [
            'invoices' => Invoice::paginate(10, pageName: 'invoices-page'),
        ]);
    }
}

これで、paginateメソッドに追加されたpageNameパラメーターにより、ユーザーが請求書2ページにアクセスすると、URLには次のものが含まれます。Now, because of the pageName parameter that has been added to the paginate method, when a user visits page 2 of the invoices, the URL will contain the following:

https://application.test/customers?page=2&invoices-page=2

名前付きページネーターでLivewireのページナビゲーションメソッドを使用する場合は、ページ名をパラメーターとして指定する必要があります。When using Livewire's page navigation methods on a named paginator, you must provide the page name as an additional parameter:

$this->setPage(2, pageName: 'invoices-page');

$this->resetPage(pageName: 'invoices-page');

$this->nextPage(pageName: 'invoices-page');

$this->previousPage(pageName: 'invoices-page');

ページ更新へのフックHooking into page updates

Livewireを使用すると、コンポーネント内で次のいずれかのメソッドを定義することにより、ページが更新される前後にコードを実行できます。Livewire allows you to execute code before and after a page is updated by defining either of the following methods inside your component:

use Livewire\WithPagination;

class ShowPosts extends Component
{
    use WithPagination;

    public function updatingPage($page)
    {
        // このコンポーネントのページが更新される前に実行されます...
    }

    public function updatedPage($page)
    {
        // このコンポーネントのページが更新された後に実行されます...
    }

    public function render()
    {
        return view('show-posts', [
            'posts' => Post::paginate(10),
        ]);
    }
}

名前付きページネーターフックNamed paginator hooks

前のフックは、デフォルトのページネーターにのみ適用されます。 名前付きページネーターを使用している場合は、ページネーターの名前を使用してメソッドを定義する必要があります。The previous hooks only apply to the default paginator. If you are using a named paginator, you must define the methods using the paginator's name.

たとえば、以下は、invoices-pageという名前のページネーターのフックがどのように見えるかの例です。For example, below is an example of what a hook for a paginator named invoices-page would look like:

public function updatingInvoicesPage($page)
{
    //
}

一般的なページネーターフックGeneral paginator hooks

フックメソッド名でページネーター名を参照したくない場合は、より一般的な代替手段を使用し、$pageNameをフックメソッドへの2番目の引数として受信できます。If you prefer to not reference the paginator name in the hook method name, you can use the more generic alternatives and simply receive the $pageName as a second argument to the hook method:

public function updatingPaginators($page, $pageName)
{
    // このコンポーネントのページが更新される前に実行されます...
}

public function updatedPaginators($page, $pageName)
{
    // このコンポーネントのページが更新された後に実行されます...
}

簡単なテーマの使用Using the simple theme

LaravelのsimplePaginate()メソッドをpaginate()の代わりに使用して、速度とシンプルさを向上させることができます。You can use Laravel's simplePaginate() method instead of paginate() for added speed and simplicity.

このメソッドを使用して結果をページネーションする場合、各ページ番号の個々のリンクの代わりに、次へおよび前へのナビゲーションリンクのみがユーザーに表示されます。When paginating results using this method, only next and previous navigation links will be shown to the user instead of individual links for each page number:

public function render()
{
    return view('show-posts', [
        'posts' => Post::simplePaginate(10),
    ]);
}

シンプルなページネーションの詳細については、Laravelの「simplePaginator」ドキュメントを確認してください。For more information on simple pagination, check out Laravel's "simplePaginator" documentation[https://laravel.com/docs/pagination#simple-pagination].

カーソルページネーションの使用Using cursor pagination

Livewireは、Laravelのカーソルページネーションもサポートしています。これは、大規模なデータセットで役立つ高速なページネーション方法です。Livewire also supports using Laravel's cursor pagination — a faster pagination method useful in large datasets:

public function render()
{
    return view('show-posts', [
        'posts' => Post::cursorPaginate(10),
    ]);
}

paginate()またはsimplePaginate()の代わりにcursorPaginate()を使用すると、アプリケーションのURLのクエリ文字列には、標準のページ番号の代わりに、エンコードされたカーソルが格納されます。 例:By using cursorPaginate() instead of paginate() or simplePaginate(), the query string in your application's URL will store an encoded cursor instead of a standard page number. For example:

https://example.com/posts?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0

カーソルページネーションの詳細については、Laravelのカーソルページネーションのドキュメントをご覧ください。For more information on cursor pagination, check out Laravel's cursor pagination documentation[https://laravel.com/docs/pagination#cursor-pagination].

Tailwindの代わりにBootstrapを使用するUsing Bootstrap instead of Tailwind

アプリケーションのCSSフレームワークとしてTailwindの代わりにBootstrapを使用している場合は、デフォルトのTailwindビューの代わりにBootstrapスタイルのページネーションビューを使用するようにLivewireを設定できます。If you are using Bootstrap[https://getbootstrap.com/] instead of Tailwind[https://tailwindcss.com/] as your application's CSS framework, you can configure Livewire to use Bootstrap styled pagination views instead of the default Tailwind views.

これを実現するには、アプリケーションのconfig/livewire.phpファイルのpagination_theme構成値を設定します。To accomplish this, set the pagination_theme configuration value in your application's config/livewire.php file:

'pagination_theme' => 'bootstrap',

lightbulb Info: Livewireの構成ファイルの発行 ページネーションテーマをカスタマイズする前に、次のコマンドを実行して、最初にLivewireの構成ファイルをアプリケーションの/configディレクトリに発行する必要があります。[!info] Publishing Livewire's configuration file Before customizing the pagination theme, you must first publish Livewire's configuration file to your application's /config directory by running the following command:

php artisan livewire:publish --config

デフォルトのページネーションビューの変更Modifying the default pagination views

アプリケーションのスタイルに合わせてLivewireのページネーションビューを変更する場合は、次のコマンドを使用して発行することで変更できます。If you want to modify Livewire's pagination views to fit your application's style, you can do so by publishing them using the following command:

php artisan livewire:publish --pagination

このコマンドを実行すると、次の4つのファイルがresources/views/vendor/livewireディレクトリに挿入されます。After running this command, the following four files will be inserted into the resources/views/vendor/livewire directory:

View file nameView file name DescriptionDescription
tailwind.blade.phptailwind.blade.php 標準のTailwindページネーションテーマThe standard Tailwind pagination theme
tailwind-simple.blade.phptailwind-simple.blade.php シンプルなTailwindページネーションテーマThe simple Tailwind pagination theme
bootstrap.blade.phpbootstrap.blade.php 標準のBootstrapページネーションテーマThe standard Bootstrap pagination theme
bootstrap-simple.blade.phpbootstrap-simple.blade.php シンプルなBootstrapページネーションテーマThe simple Bootstrap pagination theme

ファイルが発行されると、それらを完全に制御できます。 ページネーションされた結果の->links()メソッドをテンプレート内で使用してページネーションリンクをレンダリングすると、Livewireは独自のファイルの代わりにこれらのファイルを使用します。Once the files have been published, you have complete control over them. When rendering pagination links using the paginated result's ->links() method inside your template, Livewire will use these files instead of its own.

カスタムページネーションビューの使用Using custom pagination views

Livewireのページネーションビューを完全にバイパスしたい場合は、次の2つの方法のいずれかで独自のビューをレンダリングできます。If you wish to bypass Livewire's pagination views entirely, you can render your own in one of two ways:

  1. Bladeビューの->links()メソッドThe ->links() method in your Blade view
  2. コンポーネントのpaginationView()またはpaginationSimpleView()メソッドThe paginationView() or paginationSimpleView() method in your component

->links()経由Via ->links()

最初のアプローチは、カスタムページネーションBladeビュー名を->links()メソッドに直接渡すことです。The first approach is to simply pass your custom pagination Blade view name to the ->links() method directly:

{{ $posts->links('custom-pagination-links') }}

ページネーションリンクをレンダリングすると、Livewireはresources/views/custom-pagination-links.blade.phpにあるビューを探します。When rendering the pagination links, Livewire will now look for a view at resources/views/custom-pagination-links.blade.php.

paginationView()またはpaginationSimpleView()経由Via paginationView() or paginationSimpleView()

2番目のアプローチは、使用するビューの名前を返すpaginationViewまたはpaginationSimpleViewメソッドをコンポーネント内で宣言することです。The second approach is to declare a paginationView or paginationSimpleView method inside your component which returns the name of the view you would like to use:

public function paginationView()
{
    return 'custom-pagination-links-view';
}

public function paginationSimpleView()
{
    return 'custom-simple-pagination-links-view';
}

ページネーションビューのサンプルSample pagination view

以下は、参考のために、シンプルなLivewireページネーションビューのスタイルなしのサンプルです。Below is an unstyled sample of a simple Livewire pagination view for your reference.

ご覧のとおり、ボタンにwire:click="nextPage"を追加することで、$this->nextPage()のようなLivewireのページナビゲーションヘルパをテンプレート内で直接使用できます。As you can see, you can use Livewire's page navigation helpers like $this->nextPage() directly inside your template by adding wire:click="nextPage" to buttons:

<div>
    @if ($paginator->hasPages())
        <nav role="navigation" aria-label="Pagination Navigation">
            <span>
                @if ($paginator->onFirstPage())
                    <span>Previous</span>
                @else
                    <button wire:click="previousPage" wire:loading.attr="disabled" rel="prev">Previous</button>
                @endif
            </span>

            <span>
                @if ($paginator->onLastPage())
                    <span>Next</span>
                @else
                    <button wire:click="nextPage" wire:loading.attr="disabled" rel="next">Next</button>
                @endif
            </span>
        </nav>
    @endif
</div>

章選択

パッケージ

設定

バージョン変更
linkv3 linkv2
明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
OS表示
全OS表示
macOSのみ表示
windowsのみ表示
linuxのみ表示
JSフレームワーク
両フレームワーク
Reactのみ表示
Vueのみ表示
JSのみ表示

(JSが存在しない場合は、他を全表示)

和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作