0
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 1 year has passed since last update.

Laravel10 ページング機能に表示件数の可変を実装する方法

Posted at

オリジナルのページネーション表示用テンプレート

php artisan vendor:publish --tag=laravel-pagination

これでresources/views/vendor/pagination内にページネーション表示用Bladeファイルができました。

bootstrap-4.blade.php
default.blade.php
semantic-ui.blade.php
simple-bootstrap-4.blade.php
simple-default.blade.php
simple-tailwind.blade.php
tailwind.blade.php

Controller
全件取得であればall()メソッドを使うところを、paginate()メソッドに置き換え、引数に表示件数を指定

    public function index()
    {
        // all()の代わりにpagenate()を使用
        // $items = Item::all();
	$items = Item::paginate(20);
        $this->data['items'] = $items;

        return view('item.index', $this->data);
    }

viewでは作ったテンプレートファイル名を引数にすれば完了

{{ $items->links('vendor.pagination.bootstrap-4') }}

画面での選択可能にするには

Controller 画面

    public function index(Request $request)
    {

        $pag_list = [
            0 => '',
            1 => '5',
            2 => '10',
            3 => '100',
            4 => '200',
        ];

        $disp_list = $request->disp_list;

        if(empty($disp_list)) { // ?disp_list= が空値、またはURLになかった場合
            $disp_list = 3; // デフォルトの表示件数をセット
        }

        $Users = User::paginate($disp_list );
        return view('tuser.index',[  'pag_list'=>$pag_list, 'disp_list'=>$disp_list, 'Users' => $Users]);


    }

フロント画面

        <div class="form-group">
            <div class="mb-2 xl:w-66">    
                <p>総件数: {{ $Users -> total() }}</p>  
                <form action="/" method="get">                                
                    <label data-te-select-label-ref>表示件数</label>
                    <select data-te-select-init  id="disp_list" name="disp_list" value="{{ old('disp_list') }}" onchange="submit();">
                        @foreach($pag_list as $key => $val)                            
                            @if ($val === $disp_list)
                                <option value="{{ $val }}" selected >{{ $val }}</option>
                            @else
                                <option value="{{ $val }}">{{ $val }}</option>
                            @endif
                        @endforeach
                    </select>             
                
                </form>   
                {{ $Users->appends(request()->query())->links('vendor.pagination.tailwind') }}             
            </div>
        </div>
0
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
0
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?