phparrayslaravellaravel-5

Append a Laravel collection with another collection


I am trying to append an Eloquent collection with another Eloquent collection in Laravel 5.3.

This is what I've done so far:

$entries = Entry::all();
$posts   = Post::all();

$entries->merge($posts);

I tried to use merge() as shown in the code above, but it seems that I'm stuck with this kind of problem (since some of them have the same id with the same value):

Collection merge eating up some rows

Any ideas?


Solution

  • For versions < 5.4 you can merge the two eloquent collections by resetting keys with toBase like this:

    $mergedCollection = $entries->toBase()->merge($posts);
    

    For versions >= 5.4 you can use concat as suggested by Jason.