Laravel collection multiple where conditions

Viewed 31966

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
4 Answers

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;
});

Here's my solution to this issue:

    $matchThese = ['country' => 'china', 'description' => 'business'];
    $data = collect([...]);
    $query = null;

    foreach ($matchThese as $col => $value) {
        $query = ($query ?? $data)->where($col, $value);
    }

At the end of the loop, $query will contain the results.

Related