Reputation: 199
Is there a way to pass multiple where conditions into the Laravel's collection? I mean something like:
$filters = [['col1', '=', 'val1'], ['col2', '=', 'val2']];
$found = $collection->where($filters)->first();
I know it works with the eloquent query builder, but not quite with the collections. I know I can chain multiple ->where
statements (even within the foreach loop) but I need to have the original collection object, and cloning it works, but isn't so fast.
$localCollectionObject = $localCollection->first(function ($value, $key) use ($remoteCollectionObject, $compareColumnNames) {
foreach ($compareColumnNames as $compareColumnName) {
if ($value->{$compareColumnName} != $remoteCollectionObject[$compareColumnName]) {
return false;
}
}
return true;
});
This works fine also, but is even slower than clone $localCollection
.
Or maybe I can "reset" where statements somehow?
I'm searching it within foreach loop with different conditions and that's a problem.
Upvotes: 2
Views: 13569
Reputation: 35337
You can always use your own closure with filter:
$collection->filter(function ($item) {
return $item->col1 == 'val1' && $item->col2 == 'val2';
});
Upvotes: 7