cespon
cespon

Reputation: 5760

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.

Upvotes: 1

Views: 10615

Answers (3)

Hamid Raza
Hamid Raza

Reputation: 32

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

Upvotes: 0

cespon
cespon

Reputation: 5760

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

Upvotes: 4

baikho
baikho

Reputation: 5358

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.

Upvotes: 1

Related Questions