PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 4, 2022

[FIXED] How to properly merge multiple collections in Laravel

 January 04, 2022     foreach, laravel, laravel-4, laravel-5, php     No comments   

Issue

I want to merge multiple collections into one. I do have a solution, which is the following:

$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!


Solution

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


Answered By - Marcel Gruber
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing