laravel LengthAwarePaginator类不起作用

时间:2016-10-11 00:04:25

标签: php laravel pagination

我试图在laravel中手动创建一个分页,但它返回了我的模型中的所有项目,而不是“perPage”'我设置的值,下面是我的代码:

$a = mazee\ad::all();
  $p = new \Illuminate\Pagination\LengthAwarePaginator($a ,count($a),3, 1);

   dd($p) ;

所有链接:'?page = 2' ,'?page = 3' ,'?page = 4'正在输出相同的结果enter image description here

2 个答案:

答案 0 :(得分:4)

请参阅课程\Illuminate\Pagination\LengthAwarePaginator\Illuminate\Database\Query\Builder的使用示例:

/**
     * Paginate the given query into a simple paginator.
     *
     * @param  int  $perPage
     * @param  array  $columns
     * @param  string  $pageName
     * @param  int|null  $page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
    {
        $page = $page ?: Paginator::resolveCurrentPage($pageName);

        $total = $this->getCountForPagination($columns);

        $results = $total ? $this->forPage($page, $perPage)->get($columns) : [];

        return new LengthAwarePaginator($results, $total, $perPage, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => $pageName,
        ]);
    }

传递给LengthAwarePaginator的第一个参数($ results),不应该是模型中的所有行。希望它有所帮助:D

答案 1 :(得分:1)

最后我解决了这个问题:

    class maincontroller extends Controller
{
        public function getprofile(){
          $a = mazee\ad::all()->toarray();

          $this->paginate($a , 5)->items();

         }



            public function paginate($items , $perpage ){
             $total = count($items);
            $currentpage = \Request::get('page', 1);
            $offset = ($currentpage * $perpage) - $perpage ;
            $itemstoshow = array_slice($items , $offset , $perpage);
            $p = new LengthAwarePaginator($itemstoshow ,$total ,$perpage);
             $p->setPath('http://localhost/agroexpresslink.com/profile');
            return $p;
      }
}