model icon indicating copy to clipboard operation
model copied to clipboard

Collection merge does not work without an overridden getKey() method

Open Cederman opened this issue 9 years ago • 2 comments

I realised that if you want to merge two collections like this:

$collection1->merge($collection2)

You will get an exception saying that you haven't implemented a getKey() method. After som digging around, I found that, as long as you implement this method on the model and return something unique for each model instance, the merge will work.

I guess my tip is that the getKey() method is implemented in the Model.php file and that the developers using this package can provide an id attribute which is unique for all model instances :)

Cederman avatar Jan 25 '16 15:01 Cederman

This is pretty Laravel specific of course. Indeed, if you want it to be compatible with the collections, the method should be there.

jenssegers avatar Jan 25 '16 18:01 jenssegers

True indeed. But Collections is a great way to work with models and simplify things so I figured I might as well share :)

Cederman avatar Jan 25 '16 18:01 Cederman