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

rafaelmsantos's avatar

whereHas gets me an Undefined variable error

Hello everyone, I'm using the following bit of code to retrieve all "Ads" with a "Category" with certain id's.

$selected_categories = Session::get('selected_categories');
$ads = Ad::whereHas('categories', function($query){
    $query->whereIn('id', $selected_categories);
})->get();

It gives me error on the 3rd line, saying $selected_categories is not defined, I've tried:

$ads = Ad::whereHas('categories', function($query, $selected_categories){

but it still fails. It throws:

Missing argument 2 for App\Http\Controllers\FilterController::App\Http\Controllers\{closure}()

Since I'm using Sessions, I could use the Session variable, but thats not what I'm looking for. I'm expecting this to happen in places where I'll not have a Session variable to do the trick, so, how do I pass a variable here?

0 likes
3 replies
arabsight's avatar
$selected_categories = Session::get('selected_categories');
$ads = Ad::whereHas('categories', function($query) use ($selected_categories) {
    $query->whereIn('id', $selected_categories);
})->get();
2 likes
rafaelmsantos's avatar

Thanks guys, you're questions really helped me a lot. I'll accept @JarekTkaczyk answer only for the link with explanation, because booth answers were really helpfull.

Please or to participate in this conversation.