Following this post How to create multiple where clause query using Laravel Eloquent?
I am trying to insert multiple 'and' conditions:
$matchThese = ['destination.country' => 'china', 'doc.description' => 'business'];
return $collection->where($matchThese);
but I receive this error:
Too few arguments to function Illuminate\Support\Collection::where(), 1 passed . . . but two expected
Collection where
method doesn't accept an array of conditions like eloquent does. But you can chain multiple where conditions.
return $collection->where('destination.country', 'china')
->where('doc.description', 'business');
Example
$data = [
['name' => 'john', 'email' => '[email protected]'],
['name' => 'john', 'email' => '[email protected]'],
['name' => 'kary', 'email' => '[email protected]'],
];
$collection = collect($data);
$result = $collection->where('name', 'john');
// [{"name":"john","email":"[email protected]"},{"name":"john","email":"[email protected]"}]
$result = $collection->where('name', 'john')->where('email', '[email protected]');
// [{"name":"john","email":"[email protected]"}]
Chaining multiple where
s will surely work, but you will do a loop for each one of them. Use filter instead. That will loop through and check for all your conditions only once.
$matchThese = ['destination.country' => 'china', 'doc.description' => 'business'];
return $collection->filter(function ($item) use ($matchThese) {
foreach ($matchThese as $key => $value) {
if ($item[$key] !== $value) {
return false;
}
}
return true;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With