Add Laravel Collection to Another Collection

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

This is what I have done so far:

$entries = Entry::all(); $posts = Post::all(); $entries->merge($posts); 

I tried using merge() as shown in the above code, but it seems like I'm stuck with such a problem (as some of them have the same id with the same value):

The collection merges, eating several rows

Any ideas?

+9
source share
3 answers

I believe that you can combine two eloquent collections, like this:

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

After that, this is a collection with all the records.

+17
source

The merge () method gets an array, so you need to do something like

 $entries->merge($posts->toArray()); 

Laravel Collections: merge () method

0
source

I suggest that you can search for concat() . This will add one container to the end of another container, regardless of the keys of one or the other.

 $entries->concat($posts); 
0
source

Source: https://habr.com/ru/post/1264800/


All Articles