LoginSignup
6
9

More than 5 years have passed since last update.

laravelでページネーションを作る

Last updated at Posted at 2015-04-17

フレームワークによってページネーションを作る方法は異なりますが、laravelでページネーションを作るのはわりと簡単でした。

laravelでページネーションを作る

作り方としては大きく2つの方法があります。

DBの結果をページネーション

基本的にはDBの結果を以下のようにページネーションすればいい。
$article = DB::table('article')->paginate(50);

Eloquentでやる場合は
$allArticles = Article::paginate(50);
のようにする。

もちろん、whereなども使用することができる。
$allArticles = Article::where('article_type', 1)->paginate(50);

手動でページネーションを作成する

$paginator = Paginator::make($articles, $count_articles, $per_page);

ただし、$articlesがarrayの場合単純に上記のようにページネーションを作成すると
1ページ内にアイテムが全ベージ文出てしまうので以下のようにする。

$chunk_articles = array_chunk($articles, 50);
$current_page = Input::get('page', 1);
$data['result'] = Paginator::make($chunk_articles [$current_page - 1], count($chunk_articles), $per_page);

こうすることで1ページに設定したアイテム数のページネーションを作成することが出来る。

view側の実装

下準備

View::make($view, $data);

で\$viewに対象のview, \$dataにページネーションを含んだデータを入れて呼び出す。
例えば

$data['result'] = Paginator::make($chunk_articles [$current_page - 1], count($chunk_articles), $per_page);

のようにする。

view

bladeを使うとする。
配列であればforeachで回してあげて配列でとれるし

<tbody>
    @foreach($result as $res)
         <tr>
             <th>{{{$res['title']}}}</th>
        </tr>
   @endforeach
</tbody>

objならば

<tbody>
    @foreach($result as $res)
         <tr>
             <th>{{{$res->title]}}}</th>
        </tr>
   @endforeach
</tbody>

で使用することが出来る。

6
9
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
6
9