0
0

【Laravel】Illuminateにある主要メソッド Pagination編

Last updated at Posted at 2024-07-25

言語

  • Laravel8

Illuminateとは

  • Laravelが提供する様々なサービスやコンポーネントを構成するための基盤を提供している。
  • サービスやコンポーネントはIlluminate名前空間内に整理されている

どこにあるか?

プロジェクトディレクトリ\vendor\laravel\Framework\src\Illuminate\~

Illuminate\Pagination

  • Laravelのページネーション機能を提供するためのクラスがある。

paginate()

  • 指定された項目数で結果をページ分割
     $users = DB::paginate(10);
    

simplePaginate()

  • シンプルな「前へ」「次へ」リンクだけを含む簡易的なページネーション
     $users = DB::simplePaginate(10);
    

links()

  • ページネーションのリンクを生成
     {{ $users->links() }}
    

url()

  • 指定されたページ番号のURLを取得
     $url = $users->url(5);
    

appends($key, $value = null)

  • ページネーションリンクに追加のクエリ文字列パラメータを追加
     $users = DB::->paginate(10)->appends(['sort' => 'name']);
    

currentPage()

  • 現在のページ番号を取得
     $currentPage = $users->currentPage();
    

hasPages()

  • ページネーションが複数ページに分かれているかどうか確認
     if ($users->hasPages()) {
     
     }
    

hasMorePages()

  • 次のページが存在するかどうか確認
     if ($users->hasMorePages()) {
    
     }
    

count()

  • 現在のページのアイテム数を取得
     $count = $users->count();
    

total()

  • ページネーションの総アイテム数を取得
     $total = $users->total();
    

lastPage()

  • 最後のページ番号を取得
     $lastPage = $users->lastPage();
    

使用例

Controller
    use App\Models\User;

    class UserController extends Controller
    {
        public function index()
        {
            $users = User::paginate(10); //10件ごと取得

            return view('index', compact('users'));
        }
    }
blade
    <body>
        <h1>Users</h1>
        <ul>
            @foreach ($users as $user)
                <li>{{ $user->name }}</li>
            @endforeach
        </ul>
    
        {{ $users->links() }}
    </body>

私のIlluminate関連記事

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