Laravel 生成分页

生成分页数据

使用Eloquent模型的paginate方法生成分页数据.
该方法基于当前用户查看页自动设置合适的偏移(offset)和限制(limit).默认情况下,当前页通过HTTP请求查询字符串参数?page的值判断.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
namespace App\Http\Controllers;

use DB;
use App\Http\Controllers\Controller;

class UserController extends Controller{
/**
* 显示应用中的所有用户
*
* @return Response
*/
public function index()
{
$users = DB::table('users')->paginate(15);
return view('user.index', ['users' => $users]);
}
}

分页模板

下面来封装一个分页模板,调用后渲染分页
它有两个参数:
$paginator 要传入的分页数据,就是使用 paginate() 方法生成的.
$paginator_params 生成链接是添加其他的查询参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@if ($paginator->lastPage() > 1)
<nav>
<ul class="pagination pagination-sm">
<li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
@if( $paginator->currentPage() == 1 )
<span aria-hidden="true">&laquo;</span>
@else
<a href="{{ $paginator->appends($paginator_params)->url($paginator->currentPage()-1) }}" aria-label="Previous">&laquo;</a>
@endif
</li>
@for ($i = 1; $i <= $paginator->lastPage(); $i++)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->appends($paginator_params)->url($i) }}">{{ $i }}</a>
</li>
@endfor
<li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
@if( $paginator->currentPage() == $paginator->lastPage() )
<span aria-hidden="true">&raquo;</span>
@else
<a href="{{ $paginator->appends($paginator_params)->url($paginator->currentPage()+1) }}" aria-label="Next">&raquo;</a>
@endif
</li>
</ul>
</nav>
@endif

分页的辅助函数

  • $results->count()
  • $results->currentPage()
  • $results->hasMorePages()
  • $results->lastPage()
  • $results->nextPageUrl()
  • $results->perPage()
  • $results->previousPageUrl()
  • $results->total()
  • $results->url($page)
  • $paginator->appends($array)

渲染分页

现在就可以传入参数使用include 将分页渲染

1
@include('layouts/pagination', [ 'paginator' => $articles,'paginator_params' => $paginator_params ])
0%