Laravel collections merging peculiarity

Laravel collections merging failings

Laravel Eloquent collections merging fails, if initial collection has same ‘id’ as any of being merged.

Lets assume we have these Eloquent collections:

Lets assume, that $cars and $bikes have ‘id’ element with same value ‘1’.

In such case, if we do this:

… we will get elements with same value overwritten, loosing one collection element.

Here is workaround:

You create empty collection and use it as initial collection, to which you merge all others.

In this case, since your initial collection has no elements, it cannot conflict with any following collection and you get no overwrites