需要先安装 illuminate/database
和 illuminate/pagination
app/functions.php
里自定义函数use Illuminate\Pagination\UrlWindow;
use Illuminate\Pagination\LengthAwarePaginator;
if (!function_exists('paginator')) {
/**
* laravel orm 分页器
* @param LengthAwarePaginator $paginator
* @param $template
* @param $data
* @return string|null
*/
function paginator(LengthAwarePaginator $paginator, $template = 'pagination/layui', $data = [])
{
$window = UrlWindow::make($paginator);
$elements = array_filter([
$window['first'],
is_array($window['slider']) ? '...' : null,
$window['slider'],
is_array($window['last']) ? '...' : null,
$window['last'],
]);
return view($template, array_merge($data, [
'paginator' => $paginator,
'elements' => $elements,
]))->rawBody();
}
}
illuminate/pagination
自带了几个分页模板,在 vendor/illuminate/pagination/resources/views
目录可以找到。
我的项目里用的是 layui ,所以分页模板自定义了 pagination/layui.blade.php
,代码如下:
@if ($paginator->hasPages())
<div class="layui-box layui-laypage layui-laypage-default" id="layui-laypage-18">
<a class="layui-laypage-prev {{ $paginator->onFirstPage() ? 'layui-disabled' : '' }}" href="{{ $paginator->onFirstPage() ? 'javascript:void(0);' : $paginator->previousPageUrl() }}">上一页</a>
@foreach($elements as $element)
@if (is_string($element))
<span class="layui-laypage-spr">{{ $element }}</span>
@endif
@if (is_array($element))
@foreach ($element as $page => $url)
@if ($page == $paginator->currentPage())
<span class="layui-laypage-curr">
<em class="layui-laypage-em layui-bg-red"></em>
<em>{{ $page }}</em>
</span>
@else
<a href="{{ $url }}">{{ $page }}</a>
@endif
@endforeach
@endif
@endforeach
<a class="layui-laypage-next {{ !$paginator->hasMorePages() ? 'layui-disabled' : '' }}" href="{{ $paginator->hasMorePages() ? $paginator->nextPageUrl() : 'javascript:void(0);' }}">下一页</a>
</div>
@endif
// 控制器
class IndexController
{
$items = Model::query()->paginate();
return view('index/index', ['items' => $items]);
}
// 模板文件
{!! paginator($items) !!}
插个眼