Laravel 手动分页
- laravel自带的分页非常强大,仅仅调用paginate()即可取得分页,但如果我们查询的数据复杂一些,不能以paginate()为结束时,就需要手动进行一些改造,本例中得到的数据是个数组,通过分析源码,得出应该如何手动创建自己的分页。
1.手册及源码
- 根据手册,Illuminate\Pagination\Paginator 或 Illuminate\Pagination\LengthAwarePaginator 实例来实现。Paginator 类不需要知道结果集中数据项的总数;不过,正因如此,该类也没有提供获取最后一页索引的方法。LengthAwarePaginator 接收参数和 Paginator 几乎一样,只是,它要求传入结果集的总数。
- 换句话说,Paginator 对应 simplePaginate方法,而LengthAwarePaginator 对应 paginate 方法。
所以这里用后者LengthAwarePaginator来手动创建分页类。
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{
foreach ($options as $key => $value) {
$this->{$key} = $value;
}
$this->total = $total;
$this->perPage = $perPage;
$this->lastPage = (int) ceil($total / $perPage);
$this->path = $this->path != '/' ? rtrim($this->path, '/') : $this->path;
$this->currentPage = $this->setCurrentPage($currentPage, $this->pageName);
$this->items = $items instanceof Collection ? $items : Collection::make($items);
}
2.自己的分页类
- 根据对以上参数的分析,
必要参数有:
- 每页的数据$collection
- 总数 $total
- 每页数量 $per
- 当前页 $currentPage 注意必须是int型
- 分页路径 path laravel默认路径为根目录,个人觉得./为好。
顺序也一样
将自己的数组进行分页
public static function myPage($res,$per=3,$path='./')
{
$total = count($res);
$currentPage = (int)isset($_GET['page'])?$_GET['page']:1;
$collection = array_slice($res, ($currentPage-1)*$per,$per);
$page = new LengthAwarePaginator($collection,$total,$per,$currentPage,['path'=>$path]);
return $page;
}
- 以上就是我的分页,其中array_slice()第一个参数为数组,第二个参数为开始取的地方,第三个参数为取几个这样,就可以取得当前分页的数组。