1

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.

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

$qb = Item::newQuery();

if (!empty($mode))
{
    $qb->whereIn('mode_id', $mode);
}

if (!empty($type))
{
    $qb->whereIn('type_id', $type);
}

if (!empty($group))
{
    $qb->whereIn('group_id', $group);
}

$results = $qb->paginate(10);

Or build your whereIn associative array w/o empty where's before passing it on.

Comments

0

We can use array_filter to remove all falsey values:

$where = array_filter([
    'mode_id' => $mode,
    'type_id' => $type,
    'group_id' => $group
]);

$results = Item::where($where)->paginate(10);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.