I am trying to update an Eloquent collection that I've created and is containing data.
What i want to do is:
- Create a new collection
- Implement a for-each loop and add arrays with unique IDs to this collection (using an if-else condition)
- When a duplicate ID is encountered by the if-else condition, then the existing record with the same ID should have it's attributes updated by combining with the duplicate ID's attributes.
.
$fee_collection = new Collection();
$count = [];
foreach($feedetail->fee as $feee){
if(in_array($feee->id, $count)){ //check for duplicate ids
$fee_collect = $fee_collection->where('id',$feee->id)->first();
$fee_collect->pivot->amount = $fee_collect->pivot->amount + $feee->pivot->amount;
$fee_collect->pivot->line_discount = $fee_collect->pivot->line_discount + $feee->pivot->line_discount;
$fee_collect->pivot->month_year = str_replace('-28','',$fee_collect->pivot->month_year).",".str_replace('-28','',$feee->pivot->month_year);
// $fee_collection->fill($fee_collect)->save();
} else {
$fee_collection[] = $feee;
$count[] = $feee->id;
}
}
dd($fee_collect);
What i should be getting is a new collection with arrays containing merged data from the original array containing duplicated IDs.