1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelで同一ページで複数のページネーション

Posted at

Laravelで同一ページ内で複数のページネーションを実装するときのメモ

前提

  • バージョン:Laravel 6

実装方法

①第3引数に値を渡す

デフォルトでは第3引数が'page'となっているため同じページ中に複数のページネーションがあっても全て連動して動いてしまう。
これを避けるために、それぞれ別の値を渡す。

$hoge = Hoge::Paginate(5, ['*'], 'hogePage');
$funya = Funya::Paginate(5, ['*'], 'funyaPage');

②リクエストへの処理追記

①でページネーションを独立させることができるが、このままではページ遷移時に他のページネーションがリセットされてしまう。
appendsメソッドを使用して他のページネーションにも値を渡すことでこれを回避できる。

$hoge = Hoge::Paginate(5, ['*'], 'hogePage')
    ->appends(['funyaPage' => \Request::get('funyaPage')]);
$funya = Funya::Paginate(5, ['*'], 'funyaPage')
    ->appends(['hogePage' => \Request::get('hogePage')]);

結果

以下のように独立したページネーションを同一ページ内で実装できた。
paginate.gif

サンプルコード全文

DemoContoroller.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Hoge;
use App\Funya;

class DemoController extends Controller
{
    public function paginateDemo() {
        $hoges = Hoge::Paginate(5, ['*'], 'hogePage')
            ->appends(['funyaPage' => \Request::get('funyaPage')]);
        $funyas = Funya::Paginate(5, ['*'], 'funyaPage')
            ->appends(['hogePage' => \Request::get('hogePage')]);

        return view('paginateDemo',[
            'hoges' => $hoges,
            'funyas' => $funyas,
        ]);
    }
}

paginateDemo.blade.php
<!doctype html>
<html lang="ja">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <title>paginateDemo</title>
</head>

<body>
    <ul class="list-group">
        @foreach($hoges as $hoge)
            <li class='list-group-item'>{{ $hoge->name }}</li>
        @endforeach
    </ul>
    {{ $hoges->links() }}

    <ul class="list-group">
        @foreach($funyas as $funya)
            <li class='list-group-item'>{{ $funya->name }}</li>
        @endforeach
    </ul>
    {{ $funyas->links() }}
</body>

</html>
web.php
<?php
Route::get('/paginateDemo', 'DemoController@paginateDemo')->name('paginateDemo');
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?