如何对 laravel 集合进行分页?

How can i paginate laravel collection?

这是我尝试分页的方式:

$posts = Post::all()->sortByDesc("created_at")->pagination(1);

但我得到这个错误:

方法Illuminate\Database\Eloquent\Collection::分页不存在。

因为paginateBuilder方法,不是集合

您需要手动创建分页器,此处描述的方式 - https://laravel.com/docs/8.x/pagination#manually-creating-a-paginator

创建助手class

<?php

namespace App\Helpers;

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

class PaginationHelper
{
    public static function paginate(Collection $results, $showPerPage)
    {
        $pageNumber = Paginator::resolveCurrentPage('page');
        
        $totalPageNumber = $results->count();

        return self::paginator($results->forPage($pageNumber, $showPerPage), $totalPageNumber, $showPerPage, $pageNumber, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

    }

    /**
     * Create a new length-aware paginator instance.
     *
     * @param  \Illuminate\Support\Collection  $items
     * @param  int  $total
     * @param  int  $perPage
     * @param  int  $currentPage
     * @param  array  $options
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    protected static function paginator($items, $total, $perPage, $currentPage, $options)
    {
        return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
            'items', 'total', 'perPage', 'currentPage', 'options'
        ));
    }
}

打开 composer.json 文件后想要添加一个辅助文件,composer 有一个文件键(这是一个文件路径数组),你可以在自动加载中定义它

"autoload": {
    "files": [
        "app/Helpers/PaginationHelper.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\": "app/"
    }
},

现在你必须在终端中输入这个命令

composer dump-autoload

现在您可以像下面的示例一样创建分页集合

Route::get('/test_collect_pagintae', function () {

    $users = \App\User::get();

    $showPerPage = 20;

    $paginated = PaginationHelper::paginate($users, $showPerPage);

    return $paginated;
});

试试这个代码:


//convert to array
$posts = Post::all()->sortByDesc("created_at")->toArray();

//Create new pagination
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 3;
$currentItems = array_slice($posts, $perPage * ($currentPage - 1), $perPage);
//with path of current page
$posts = (new LengthAwarePaginator($currentItems, count($posts ), $perPage, $currentPage))->setPath(route('posts....'));

//Convert array of array to array of object
$posts->each(function ($item, $itemKey) use($posts) {
     $posts[$itemKey] = (Object)$item;
});

您可以在 app/provider/serviceProvider 方法 boot

中使用此代码
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,
                ]
            );
        });

SOLUTION

这是来自 simonhamp 的非常好的解决方案,谢谢 simonhamp

我的建议是像下面这样在 AppServiceProvider 中执行 ->values()。这很重要,因为当切片集合时,键被保留,我们不希望它用于分页器。

Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
    $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

    return new LengthAwarePaginator(
        $total ? $this : $this->forPage($page, $perPage)->values(),
        $total ?: $this->count(),
        $perPage,
        $page,
        [
            'path' => LengthAwarePaginator::resolveCurrentPath(),
            'pageName' => $pageName,
        ]
    );
});