Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection multiple where conditions

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
like image 881
Stefano Maglione Avatar asked Jun 01 '17 12:06

Stefano Maglione


2 Answers

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]"}]
like image 60
Sandeesh Avatar answered Sep 19 '22 11:09

Sandeesh


Chaining multiple wheres 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;
});
like image 32
Guillaume Boutin Avatar answered Sep 19 '22 11:09

Guillaume Boutin