1
1

More than 3 years have passed since last update.

Laravelでページネーション実装

Posted at

前提

PHP Laravel
7.1.19 5.6.27

使用方法

LaravelのペジネータはクエリビルダとEloquent ORMに統合されている。
今回はpagenateメソッドを用いることとする。

クエリビルダ

下記のように、paginateに一つだけ引数を渡しており、今回はページごとに10アイテムを表示するように指定している。

<?php

namespace App\Http\Controllers;

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

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

        return view('user.index', compact('users');
    }
}

Eloquent

Eloquentモデルも同様にpagenateメソッドを用いる。

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

$users = User::where('name', '太郎')->paginate(10);

$users = User::orderBy('created_at', 'desc')->paginate(10);

ページネーション表示

pagenateメソッドはIlluminate\Pagination\LengthAwarePaginatorインスタンスを返すので
、その結果をBladeに渡して、結果を表示する。

{{ $users->appends(request()->query())->links() }}

・appends

ペジネーションリンクにクエリ文字列を付加する。
クエリ文字列は「https:// ○△×□.jp/?hoge=hogehoge」の「?hoge=hogehoge」の部分

・request

現在のリクエストインスタンス(Illuminate\Http\Request)を返す。

・query

request()->query()でクエリ文字列を取得する。

・links

 検索結果の残りのページヘのリンクを付加する。各リンクにはpageクエリ文字列変数が含まれている。

参考

https://readouble.com/laravel/5.8/ja/pagination.html

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