LoginSignup
27
23

More than 5 years have passed since last update.

Laravel5.7: ページネーションの機能を追加する

Last updated at Posted at 2017-05-27

下記のように、1ページに表示する投稿数を限定して、ページを切り替えるリンクを設置します。

pagination.png

親記事

Laravel 5.7で基本的なCRUDを作る - Qiita

indexアクションにページネーションを追加

:link: readouble.com: ペジネーション

コントローラ

各コントローラのindexアクションを下記のように修正します。
今回は1ページに5件表示するようにします。

app/Http/Controllers/UserController.php
    // ユーザー
    public function index()
    {
-       $users = User::all();
+       $users = User::paginate(5);
app/Http/Controllers/PostController.php
    // 投稿記事
    public function index()
    {
-       $posts = Post::latest()->get();
+       $posts = Post::latest()->paginate(5);

ビュー

それぞれ、Bootstrapの.containerの終了タグの直前にページリンクを設置します。

resources/views/users/index.blade.php
    {{ $users->links() }}
</div><!-- .container の終了タグ -->
resources/views/posts/index.blade.php
    {{ $posts->links() }}
</div><!-- .container の終了タグ -->

見た目を細かく変更したい場合は、公式解説でも勧めているとおりvendor:publishコマンドを使うのがいいと思います。
:link: readouble.com: ペジネーションビューのカスタマイズ

27
23
1

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
27
23