我想把多个Collection 合并成一个.我有一个解决方案,如下所示:

$allItems = $collection1->merge($collection2)
                        ->merge($collection3)
                        ->merge($collection4)
                        ->merge($collection5);

This actually does work, but I run into problems in cases where some or all of the collections contain no objects. I get an error along the lines of call to merge() on non object.

I actually tried to create an array of all of the collections, and then iterate through them, while checking their validity, but it didn't work and I feel it wasn't very elegant.

How can I elegantly iterate through this process of merging multiple collections, while taking into account that some or all of the collections might be empty or invalid? Appreciated!

推荐答案

What I ended up doing was separating each step. It was the merge chaining that was killing it, because some or all of the collections could have been invalid.

$allItems = new \Illuminate\Database\Eloquent\Collection; //Create empty collection which we know has the merge() method
$allItems = $allItems->merge($collection1);
$allItems = $allItems->merge($collection2);
$allItems = $allItems->merge($collection3);
$allItems = $allItems->merge($collection4);

Laravel相关问答推荐

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

嵌套数组请求的 Laravel 验证,其中如果整数之一为零,则另一个应大于零

如何计算具有特定 ID Laravel 的行

laravel 如何验证跨越午夜的两个值之间的时间(15:00 > 时间 > 01:00)

如何防止 Laravel 路由被直接访问(即非 ajax 请求)

Laravel:如何强制使用 HTTPS?

未捕获的 TypeError:Vue.component 不是函数

Laravel + Plupload 上传到 S3 响应以进行预检无效 - CORS

Laravel 5.4 - 如何为同一个自定义验证规则使用多个错误消息

Laravel,没有shell 访问的转储自动加载

Laravel 价格验证只接受正数而不是 0

Laravel - 排序的集合输出不是数组

控制器中的 Laravel Auth 用户 ID

Laravel timestamps() 不会创建 CURRENT_TIMESTAMP

如何处理 laravel 5 中的私有图像?

Laravel 5 环境配置数组?

Laravel 项目旁边的 Wordpress 项目(在 public_html 文件夹中)

是否可以将路由参数传递给 Laravel 中的控制器构造函数?

laravel如何访问具有表编号名称的列?

在 laravel Passport 客户端应用程序中使用访问令牌获取用户数据