0

I have three collections.

SalaryCollection

enter image description here

BonusCollection

enter image description here

Deduction Collection

enter image description here

All of them have date which is common in some of them. I want to merge these three into one collection in a way that object with same date in three becomes one as a result. Something like this:

#items:array:2[
0=>{
+"date":"1-2020"
+"salaries":36500.0
+"deductions":1500.0
+"bonuses":7000.0
}
1=>{
+"date":"2-2020"
+"salaries":20000.0
+"deductions":1000.0
+"bonuses":5000.0
}
]

How can i do it?

Abdulmoiz Ahmer
  • 1,953
  • 17
  • 39

1 Answers1

0

I am not sure if this is the best way to do it but this is how i made it worked.

     $salaryCollection = $salaryCollection->map(function ($item, $key) use ($bonusCollection) {
        $single_bonus = $bonusCollection->where('date', $item->date);
        if (!$single_bonus->isEmpty()) {
            return collect($item)->put('bonuses', $single_bonus->first()->bonuses);
        } else {
            return collect($item)->put('bonuses', 0);
        }
    });

    $salaryCollection = $salaryCollection->map(function ($item, $key) use ($deductionCollection) {
        $single_deduction = $deductionCollection->where('date', $item['date']);
        if (!$single_deduction->isEmpty()) {
            return collect($item)->put('deductions', $single_deduction->first()->deductions);
        } else {
            return collect($item)->put('deductions', 0);
        }
    });
Abdulmoiz Ahmer
  • 1,953
  • 17
  • 39