$selected_categories = Session::get('selected_categories');
$ads = Ad::whereHas('categories', function($query) use ($selected_categories) {
$query->whereIn('id', $selected_categories);
})->get();
Apr 28, 2015
3
Level 1
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?
Level 53
@rafaelmsantos Read about the scopes in closure http://php.net/manual/en/functions.anonymous.php
tldr;
function ($q) use ($whateverYouNeedInClosure) {
$whateverYouNeedInClosure; // OK now
}
2 likes
Please or to participate in this conversation.