【问题标题】:Laravel pagination not working with array instead of collectionLaravel 分页不适用于数组而不是集合
【发布时间】:2015-08-09 06:29:34
【问题描述】:

我正在尝试对数组数据集进行分页,事实证明它比我想象的更具挑战性。

我正在使用 Laravel 5

所以我有一个抽象接口/存储库,我的所有其他模型都扩展到该抽象接口/存储库,并且我在我的抽象存储库调用 paginate 中创建了一个方法。 我已经包括了两个

use Illuminate\Pagination\Paginator;

use Illuminate\Pagination\LengthAwarePaginator;

方法如下

  public function paginate($items,$perPage,$pageStart=1)
    {

        // Start displaying items from this number;
        $offSet = ($pageStart * $perPage) - $perPage; 

        // Get only the items you need using array_slice
        $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);

        return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }

因此,您可以想象,此函数接受 $items 数组,$perPage 变量表示要分页的项目数,$pageStart 表示从哪个页面开始。

分页有效,当我执行 dd() 时,我可以看到 LengthAwarePaginator 实例,它的所有值似乎都很好。

当我显示结果时问题就开始了。

当我做{!! $instances->render() !!}分页器链接显示很好时,page参数会根据链接而变化,但数据没有变化。 每一页的数据都是一样的。当我使用 Eloquent 例如 Model::paginate(3) 时,一切正常,但是当我 dd() 这个 LengthAwarePaginator 它与我的自定义分页器的 LengthAwarePaginator 实例相同,除了它对数组进行分页而不是集合.

【问题讨论】:

    标签: laravel laravel-5 laravel-pagination


    【解决方案1】:

    你没有像你应该的那样传递当前页面,所以你也得到了相同的数组。这将起作用

    public function paginate($items,$perPage)
    {
        $pageStart = \Request::get('page', 1);
        // Start displaying items from this number;
        $offSet = ($pageStart * $perPage) - $perPage; 
    
        // Get only the items you need using array_slice
        $itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
    
        return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
    }
    

    如果您为 $pageStart - Request::get('page', 1) 传递正确的值,您的函数也将起作用

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 2018-12-07
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多