phplaravel-5.3

Laravel array whereIn()


I have a form to filter items:

filter

and I'm looking for something similar to this in Laravel 5.3:

// some variables get from request()->input('...')
$mode = ['A'];
$type = ['a', 'b'];
$group = [0, 1];

// desirable query
$results = Item::whereIn([
    ['mode_id', $mode],
    ['type_id', $type],
    ['group_id', $group]
])->paginate(10);

I can do this

$results = Item::whereIn('mode_id', $mode)
               ->whereIn('type_id', $type)
               ->whereIn('group_id', $group)
               ->paginate(10);

but it's not a dynamic way. For example, if a user select nothing in mode, the query returns an empty array.


Solution

  • We can use conditional clauses:

    $results = Item::
        when(!empty($mode), function ($query) use ($mode) {
            return $query->where('mode_id', $mode);
        })
        ->when(!empty($type), function ($query) use ($type) {
            return $query->where('type_id', $type);
        })
        ->when(!empty($group), function ($query) use ($group) {
            return $query->where('group_id', $group);
        })
        ->paginate(10);