Reputation: 1059
I have two collections to compare:
$collection1 = collect([
'alex',
'john'
]);
$collection2 = collect([
[
'id' => 1,
'name' => 'alex',
],
[
'id' => 2,
'name' => 'john',
],
[
'id' => 3,
'name' => 'joe',
],
]);
I want to compare collection2
with $collection1
and only get items which the name
value doesnt in the other collection, the result i want:
[
'id' => 3,
'name' => 'joe',
]
But the problem is the first collection have flat array so, i did this:
$collection2->diffUsing($collection1, function ($a, $b){
return strcmp($a['name'], $b);
});
But i get the error :
ErrorException : strcmp() expects parameter 2 to be string, array given
Upvotes: 2
Views: 1161
Reputation: 50491
You can use whereNotIn
to do this, passing the first collection as the values you want to filter out:
$result = $collect2->whereNotIn('name', $collect1);
Laravel 8.x Docs - Collections - Available Methods - whereNotIn
Upvotes: 3