Laravel 手动分页

Laravel 手动分页

  • laravel自带的分页非常强大,仅仅调用paginate()即可取得分页,但如果我们查询的数据复杂一些,不能以paginate()为结束时,就需要手动进行一些改造,本例中得到的数据是个数组,通过分析源码,得出应该如何手动创建自己的分页。

1.手册及源码

  • 根据手册,Illuminate\Pagination\Paginator 或 Illuminate\Pagination\LengthAwarePaginator 实例来实现。Paginator 类不需要知道结果集中数据项的总数;不过,正因如此,该类也没有提供获取最后一页索引的方法。LengthAwarePaginator 接收参数和 Paginator 几乎一样,只是,它要求传入结果集的总数。
  • 换句话说,Paginator 对应 simplePaginate方法,而LengthAwarePaginator 对应 paginate 方法。
    所以这里用后者LengthAwarePaginator来手动创建分页类。
//LengthAwarePaginator源码 vendor\laravel\framework\src\Illuminate\Pagination
    /**
     * Create a new paginator instance. 
     * 
     * @param  mixed  $items 查询的结果
     * @param  int  $total  查询的总是
     * @param  int  $perPage 每页个数
     * @param  int|null  $currentPage 当前页
     * @param  array  $options (path, query, fragment, pageName)  路径 暂不清楚 暂不清楚 分页关键字
     * @return void 没有返回
     */
    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默认路径为根目录,个人觉得./为好。
      顺序也一样
      将自己的数组进行分页
    /*
     * Create myPage
     *
     * @param array $res
     * @param int $per
     * @param string $path
     */
    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()第一个参数为数组,第二个参数为开始取的地方,第三个参数为取几个这样,就可以取得当前分页的数组。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值