提问者:小点点

如何在Laravel 5中为合并的集合分页?


我正在创建一个包含两种类型对象的流,BluePerson和RedPerson。为了创建流,我获取所有两个对象,然后将它们合并到一个集合中。这样做之后,我需要对它们进行分页,然而分页是针对雄辩的模型和数据库查询的,而不是集合。我已经看到了很多关于手动创建分页器,但是留档,尤其是在API中是稀疏的(我甚至似乎找不到Paginator类接受的参数。)

如何对合并收藏的结果进行分页?

public function index()
{
    $bluePerson = BluePerson::all();
    $redPerson = RedPerson::all();

    $people = $bluePerson->merge($redPerson)->sortByDesc('created_at');


    return view('stream.index')->with('people', $people);
}

共3个答案

匿名用户

然而,paginate似乎是用于雄辩的模型和DB查询,而不是集合。

你是对的。但是有一个用于收藏的分页器函数。forPage

Collection forPage(int $page, int $perPage)

Rest很简单。

public function foo()
{
    $collection = collect([1,2,3,4,5,6,7,8,9,0]);
    $items = $collection->forPage($_GET['page'], 5); //Filter the page var
    dd($items);
}

匿名用户

如果您想使用LengthAware Paginator,只需实例化一个。正如前面回答的评论中提到的,你必须为此设置路径。在实例化分页器之前,您还需要确保解析“当前页”并设置要返回的项。这都可以在实例化之前/在实例化时完成。所以一个函数可能看起来像:

function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
    $currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
    $currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage);
    parse_str(request()->getQueryString(), $query);
    unset($query[$pageName]);
    $paginator = new \Illuminate\Pagination\LengthAwarePaginator(
        $currentPageItems,
        $collection->count(),
        $perPage,
        $currentPage,
        [
            'pageName' => $pageName,
            'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
            'query' => $query,
            'fragment' => $fragment
        ]
    );

    return $paginator;
}

匿名用户

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;

您可以在公共函数引导()中的提供程序/AppService提供程序中添加以下集合代码。

    // Enable pagination
    if (!Collection::hasMacro('paginate')) {

        Collection::macro('paginate', 
            function ($perPage = 15, $page = null, $options = []) {
            $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
            return (new LengthAwarePaginator(
                $this->forPage($page, $perPage)->values()->all(), $this->count(), $perPage, $page, $options))
                ->withPath('');
        });
    }

然后,您可以从集合中调用paginate,就像一个雄辩的模型一样。例如

$pages = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->paginate(5);