Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

550
Views
Join 2 laravel collections

I have 2 collections :

$collection1 = [ 
{ name : "aaa" , score : 10 },
{ name : "bbb" , score : 20 }
];
$collection2 = [ 
{ name : "aaa" , score : 30 },
{ name : "bbb" , score : 10 }
];

and I want to join them to get the following result :

$collection3 = [ 
{ name : "aaa" , score : 40 },
{ name : "bbb" , score : 30 }
]

merge() and union() didn't do the job for me .

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Combine the collections, group by the name and sum the score. This can be done like so with collections in Laravel. Note that group by returns a collection of the grouped data.

$collection1->concat($collection2);

$collection1->groupBy('name')->map(function ($scores) {
    $score = $scores->first();

    $score['score'] = $scores->sum('score');

    return $score;
});
over 4 years ago · Santiago Trujillo Report

0

it can be achieve by laravel collection map() and where() function

$collection1 = collect([
    [
        "name" => "aaa",
        "score" => 10
    ],
    [
        "name" => "bbb",
        "score" => 20
    ]
]);
$collection2 = collect([
    [
        "name" => "aaa",
        "score" => 30
    ],
    [
        "name" => "bbb",
        "score" => 10
    ]
]);

$collection3 = $collection1->map(function ($item) use ($collection2) {
        $found = $collection2->where('name', $item['name']);
        if ($found) {
            $item['score'] = $item['score'] + $found->first()['score'];
        }
        return $item;
    });

dd($collection3);

This is the result https://phpsandbox.io/n/soft-flower-ap1e-vo2xy

over 4 years ago · Santiago Trujillo Report

0

$collection = collect();$collection->merge(['col1' => $col1, 'col2' => $col2 ]); OR $states = [ 'Delhi', 'Tamil Nadu', 'Uttar Pradesh']; foreach ($states as $state) { $data = DB::table('user')->select('user.*') ->where("user.city", $state)->where('user.status', 1)->get(); if (!empty($data[0])) $stateUser = $stateUser->merge([$state => $data]);}

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!