LoginSignup
1
1

More than 1 year has passed since last update.

Laravelによるページネーションの書き方

Last updated at Posted at 2022-09-11

ページネーション(pagination)とは

  • 検索結果やデータベースの一覧画面などを適度な長さで分割して表示する仕組み
  • 次の画像のように各ページへのリンクを並べることでアクセスしやすくなります
  • 10件ずつ表示する、50件ずつ表示するなど、表示数をカスタマイズできます

見本:Google検索結果より
スクリーンショット 2022-09-12 7.56.59.png

環境について

データベース内にuserというテーブルが存在する仮定で以下の手順は進みます

作成方法

データベースのテーブル情報を取得するモデルを作成します

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
    {
  
    }
namespace App;

use Illuminate\Database\Eloquent\Model;

class 任意のモデル名 extends Model
    {
  
    }

コントローラーでビューにモデルの情報を送ります

    class HomeController extends Controller
{
  
    public function index()
    {
        $users = Users::paginate(5);
        return view('layout.index',['users' => $users]);
        /*もしくは*/
        /* return view('layout.index')->with('users',$users); */
    }
}

    class HomeController extends Controller
{
  
    public function index()
    {
        $任意の変数名 = 存在するモデル名::paginate(何個でページを分割するか);
        return view('ビューが存在するディレクトリ名.ビューのファイル名',['$を抜いた変数名' => $を付けた変数名]);
        
    }
}

ビューに情報を表示します(例)

<!--テーブル-->
    <div class="table-responsive">
        <table class="table" style="width: 1000px; max-width: 0 auto;">
              <tr class="table-info">
              <th scope="col" >id</th>
                <th scope="col" >商品画像</th>
                <th scope="col" >商品名</th>
                <th scope="col" >価格</th>
                <th scope="col" >在庫数</th>
                <th scope="col" >メーカー名</th>
                <th scope="col" >詳細表示</th>
                <th scope="col" >削除</th>
              </tr>
              @foreach($users as $user)
              <tr>
                <td>{{$user->id}}</td>
                <td>{{$user->img_path}}</td>
                <td>{{$user->product_name}}</td>
                <td>{{$user->price}}</td>
                <td>{{$user->stock}}</td>
                <td>{{$user->company_name}}</td>
                <td><button type="button" class="btn btn-success">詳細</button></td>
                <td><button type="button" class="btn btn-danger">削除</button></td>
              </tr>
              @endforeach
          </table>
     </div>
     {!! $users->render() !!}
 /* テーブルのdevタグなどの外側へ
{!! $users->render() !!}
を追記します */

{!! $コントローラーから受け取った$変数名->render() !!}

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