I want to see if I have differing ids when I grab data using two different data sets. Not what I need for but for example, I want to see all people that ordered product A and all people that ordered product B and then see which only ordered A or B.
So, I have $Collection1 which, when dumped looks like this:
Illuminate\Support\Collection {#3031 ▼
#items: array:1 [▼
0 => 14066
]
#escapeWhenCastingToString: false
}
Then my $Collection2 looks like this:
Illuminate\Support\Collection {#3000 ▼
#items: array:3 [▼
2 => 13147
0 => 14066
1 => 14066
]
#escapeWhenCastingToString: false
}
I expect when I do $Collection1->diff($Collection2)
that I'll get a collection that has 13147 as an item in it.
What I get is this:
Illuminate\Support\Collection {#2998 ▼
#items: []
#escapeWhenCastingToString: false
}
Any idea what I could be doing wrong?
Thanks so much.
CodePudding user response:
As described in the Laravel documentation:
"The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection"
https://laravel.com/docs/9.x/collections#method-diff
So comparing an empty collection with another collection will always return empty, as in your case. You should then compare the collection that do have values in order to get your desired result
CodePudding user response:
$Collection1->diff($Collection2)
means (collection1 - collection2)
but you wont (collection1 - collection2) (collectio2 - collection1)
write like this:
$diff1 = $Collection1->diff($Collection2);
$diff2 = $Collection2->diff($Collection1);
$result = $diff1->merge($diff2);