Merge Two Collections Containing Same IDs In Laravel

Let’s say you have two Collections with the same ID.

$a = collect([ 'id' => 1, 'name' => 'Johnny' ]);
$b = collect([ 'id' => 1, 'age' => 14 ]);

There’s not a helper to merge the two for a result like this.

$c = [ 'id' => 1, 'name' => 'Johnny', 'age' => 14];

But you can merge the two using toBase() and merge().

$c = $a->map( function($row) use ($b){
  $age = $b->where('id'', $row->id)->pluck('sales);
  return collect($row)->put('age', $age);

Honestly, I don’t know if this is the most efficient method. Seems like there should be a better way. But there are more forums talking about merging collections despite the same id.

Leave a Comment