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. After doing so, I need to paginate them, however paginate is for eloquent models and DB queries, and not collections, it seems. I have seen a lot about manually creating a paginator, but the documentation, especially in the API is sparse (I can't even seem to find the arguments the Paginator class accepts.)

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

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

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


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

推荐答案

however paginate is for eloquent models and DB queries, and not collections, it seems.

You are right. but there is ineed a paginator function for collections. forPage

语法:

Collection forPage(int $page, int $perPage)

示例:

休息很简单.

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);
}

Laravel相关问答推荐

如何判断用户是否已登录Laravel

Laravel:通过数据透视表数据限制多对多Eager 加载

如何在 Laravel 中使用多对一变形关系

将错误消息抛出并显示为关联数组

我在 laravel 中插入多个复选框值.我怎样才能做到这一点?

在 Laravel 中设置多个 Vue 组件的问题

Laravel | 使用select查询

Laravel 5 - 仅在特定页面/控制器(页面特定assets资源)上添加样式表

如何在 Laravel 中显示渲染时间/页面加载时间?

Laravel Eloquent:访问属性和动态表名

带有消息...必须返回关系实例的 LogicException.

如何从 Laravel 中的 hasMany() 关系中获取所有结果?

Laravel 判断约束违规

laravel 队列 - 同步驱动程序如何工作?它是在单独的进程/线程还是主执行线程中执行?

无法声明类 Controller,因为该名称已在使用中

在 Laravel 中翻译特定语言

Laravel 如何在 Eloquent 模型中添加自定义函数?

带有 Xdebug 的 Laravel 5 总是抛出The payload is invalid..

如何从 laravel 5.1 中数据库表的 created_at 属性中 Select 年份和月份?

Laravel:Redis 无法建立连接:[tcp://127.0.0.1:6379]