Joe Spurling
Joe Spurling

Reputation: 977

How to combine multiple Eloquent collections in Laravel

I have various models that I would like to combine into one (for output into a DataTables instance).

So far I have done this (in reality there are about 15 models, I'm just showing two here):

$all_records = new Collection;

$care_plan_updates = \App\CarePlanUpdate::where('resident_id', $resident->id)->where('closed','0')->get();
if($care_plan_updates) $all_records = $all_records->merge($care_plan_updates);  

$medication_errors = \App\MedicationError::where('resident_id', $resident->id)->where('closed','0')->get();
if($medication_errors) $all_records = $all_records->merge($medication_errors);

return Datatables::of($all_records)

On first impressions this seemed to have done the trick well. However, I've noticed that the merge method combines records that share an ID value. So for example, the CarePlanUpdate with an ID of 12 is overridden by the MedicationError record with the ID of 12.

I have tried 'forgetting' the ID column but this doesn't seem to have any effect:

if($care_plan_updates) $all_records = $all_records->merge($care_plan_updates->forget('id'));

Ideally, I'd like a method that simply combines two collections without merging rows with duplicate values. I'm new to Eloquent - so any guidance on where I'm going wrong would be really appreciated!

Upvotes: 1

Views: 2725

Answers (1)

Joe Spurling
Joe Spurling

Reputation: 977

I have found a solution. I'm not sure it's the most elegant way of achieving my goal though but it does the trick:

Rather than using the merge collection method I decided to loop through each individual collection and use push to add each record to my master collection. Like so:

$all_records = new Collection;

$care_plan_updates = \App\CarePlanUpdate::where('resident_id', $resident->id)->where('closed','0')->get();  
foreach($care_plan_updates as $care_plan_update) {
    $all_records->push($care_plan_update);
}   

$risk_assessment_updates = \App\RiskAssessmentUpdate::where('resident_id', $resident->id)->where('closed','0')->get();
foreach($risk_assessment_updates as $risk_assessment_update) {
    $all_records->push($risk_assessment_update);
} 

Upvotes: 3

Related Questions