mikkelbfriis's avatar

Laravel collection merge removes an item?

Hiya, casts! I've recently been trying to figure out why my eloquent->merge removes an item?

$value['city'] = 'København';

$advertisements = App\Advertisement::whereHas('property', function ($q) use ($value) {
    return $q->where('city', 'LIKE', '%' . $value['city'] . '%');
})->take(4)->get();

$query = App\Property::where('city', 'LIKE', '%' . $value['city'] . '%')->whereDoesntHave('advertisement')->inRandomOrder()->take(4 - $advertisements->count());

$properties = $query->get();

$collection = $properties->merge($advertisements);

Sometimes it'll have the 4 it needs, however at some points it'll just return 3 items that's been merged. How can this be?

I've also tried dd'ing almost everything in the code:

dd([$collection, $properties, $advertisements, 4 - $advertisements->count(), $query]);

There's no duplicates, this I've tested severely to make sure there wasn't.

The merge is when there's not enough properties in the advertisements, so it's kind-of a fallback method.

0 likes
5 replies
arukomp's avatar

Is it random when using the same city again and again? Or is it possible that one of the cities just doesn't have 4 properties+advertisements?

1 like
staudenmeir's avatar

When merging Eloquent collections, models with the same primary key are seen as duplicates (even with different classes).

You can prevent this by converting the first one to a base collection:

$collection = $properties->toBase()->merge($advertisements);
8 likes
mikkelbfriis's avatar

Hi. Somehow merging two different models, ended up doing something wrong. So what I’ve decided is to pluck only the property from the advertisement and then merge those. But thanks!

Please or to participate in this conversation.