Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ollie_123's avatar

when query not seeing variable with array

Hi All

I've got an $options variable that is sometimes populated with an array... when its not null i would like the query to find the matching array of ID's but currently its throwing an undefined $options variable error.

$options = LineItem::where('category_id', '2')->pluck('option_id');
...
->when($options, function($query) {
    return $query->whereIn('line_items.option_id', $options->option_id);
})
...

Please can someone advise where im going wrong.

Thanks in advance.

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@ollie_123 You need to pass $options inside the closure.

->when($options, function($query) use ($options) {
    return $query->whereIn('line_items.option_id', $options);
})

Please or to participate in this conversation.