How can I paginate a merged collection in Laravel 5?

后端 未结 7 1540
温柔的废话
温柔的废话 2020-12-02 14:31

I am creating a stream which contains two types of objects, BluePerson and RedPerson. To create the stream, I fetch all of both objects, then merge them into one collection.

7条回答
  •  难免孤独
    2020-12-02 15:18

    best way for paginate collection:

    1- add this to boot function in \app\Providers\AppServiceProvider

           /*
             * use Illuminate\Support\Collection;
             * use Illuminate\Pagination\LengthAwarePaginator;
             *
             * Paginate a standard Laravel Collection.
             *
             * @param int $perPage
             * @param int $total
             * @param int $page
             * @param string $pageName
             * @return array
             */
            Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
                $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
                return new LengthAwarePaginator(
                    $this->forPage($page, $perPage),
                    $total ?: $this->count(),
                    $perPage,
                    $page,
                    [
                        'path' => LengthAwarePaginator::resolveCurrentPath(),
                        'pageName' => $pageName,
                    ]
                );
            });
    

    2-From hereafter for all collection you can paginate like your code

    $people->paginate(5)
    

提交回复
热议问题